8 File
8 File
What is Stream ?
Stream must be associated with each file to be manipulated.
Stream were invented in very early days of C when devices were slow . Programs executing in memory run much faster then
hardware devices can provide the information they need. It was found that when a program read characters individually form a
disk , the program would have to wait excessively for the correct part of the disk , the program would have to wait excessively for
the correct part of the disk to spin around. The character would be grabbed and processed then the program would have to wait
again for the disk.
Caches
In the intervening years manufacturers have invented caches so the disk never reads a single character. Thus when the program
requests the next character it is provided immediately from the buffer. Complex alogorithms are used to determine which character
should be buffered and which should be discarded.
Streams do this buffering in software. Thus if the device you are using does not support caching, it doesnt matter because the
stream will do it for you.
Text Streams
A text stream transports the characters of a text that is divided into lines. A line of text consists of a sequence of characters ending in
a newline character. A line of text can also be empty, meaning that it consists of a newline character only. The last line transported
may or may not have to end with a newline character, depending on the implementation.
Binary Streams
A binary stream is a sequence of bytes that are transmitted without modification. In other words, the I/O functions do not involve
any interpretation of control characters when operating on binary streams . Data written to a file through a binary stream can always
be read back unchanged on the same system. However, in certain implementations there may be additional zero-valued bytes
appended at the end of the stream.
Whether char is signed or unsigned. This seems rather irrelevant until it is revealed that the value of the EOF is 1. Now if a
compiler chose to implement char as an unsigned quantity when getchar returned 1 to indicate end of file , it would casues 255 to
be stored. When the 255 were compared with the 1 value of EOF the comparison would fail
Opening Files
Opening and Closing Files
To write to a new file or modify the contents of an existing file, you must first open the file. When you open a file, you must specify
an access mode indicating whether you plan to read, to write, or some combination of the two. When you have finished using a file,
close it to release resources.
Access Modes
The access mode specified by the second argument to fopen( ) or freopen( ) determines what input and output operations
the new stream permits. The permissible values of the mode string are restricted.
The first character in the mode string is always r for "read," w for "write," or a for "append," and in the simplest case, the string
contains just that one character. However, the mode string may also contain one or both of the characters + and b (in either order:
+b has the same effect as b+).
A plus sign (+) in the mode string means that both read and write operations are permitted. However, a program must not alternate
immediately between reading and writing. After a write operation, you must call the fflush( ) function or a positioning function
(fseek( ), fsetpos( ), or rewind( )) before performing a read operation. After a read operation, you must call a
positioning function before performing a write operation.
A b in the mode string causes the file to be opened in binary mode that is, the new stream associated with the file is a binary stream.
If there is no b in the mode string, the new stream is a text stream.
If the mode string begins with r, the file must already exist in the file system.
If the mode string begins with w, then the file will be created if it does not already exist. If it does exist, its previous contents will be
lost, because the fopen( ) function truncates it to zero length in "write" mode.
A mode string beginning with a (for append) also causes the file to be created if it does not already exist. If the file does exist,
however, its contents are preserved, because all write operations are automatically performed at the end of the file. Here is a brief
example:
Closing file
The function flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the stream's
input and output buffers. The fclose( ) function returns zero on success, or EOF if an error occurs.
When the program exits, all open files are closed automatically. Nonetheless, you should always close any file that you have
finished processing. Otherwise, you risk losing data in the case of an abnormal program termination.
Files are opened and streams created with the fopen function.
Before a file may be manipulated a stream must be associated with it. This association between stream and file is made with the
fopen routine.
All that is needed is to plug in the file name, the access mode(read, write, append) and the stream comes back..
A stream is actually declared as FILE * i.e. a pointer to a FILE structure.
Formatted file input/output deals with text and numeric data that is formatted in a specific way.
Displaying a File
#include <stdio.h> if((in_stream=fopen(in_name,"r"))==NULL)
#include <conio.h> {
void main() fprintf(stderr,"open of %s for reading failed",in_name);
{ perror(" because ");
char in_name[80]; }
FILE *in_stream; while((ch=fgetc(in_stream))!=EOF)
int ch; putchar(ch);
clrscr(); fclose(in_stream);
printf("Display file : "); getch();
scanf("%79s",in_name); }
make a text file in c drive give full address for example c:\as.txt
%79 prevent the user from corrupting memory if more than 79 characters are typed.
Fopen wb:- wb opeion puts the steam into binary write mode
Direct File Input and Output
Direct I/O is used only with binary-mode files. With direct output, blocks of data are written from memory to disk. Direct input
reverses the process: A block of data is read from a disk file into memory. For example, a single direct-output function call can write
an entire array of type double to disk, and a single direct-input function call can read the entire array from disk back into memory.
The direct I/O functions are fread() and fwrite().
The fwrite() Function
The fwrite() library function writes a block of data from memory to a binary-mode file. Its prototype in STDIO.H is
int fwrite(void *buf, int size, int count, FILE *fp);
The argument buf is a pointer to the region of memory holding the data to be written to the file. The pointer type is void; it can be a
pointer to anything.
The argument size specifies the size, in bytes, of the individual data items, and count specifies the number of items to be written. For
example, if you wanted to save a 100-element integer array, size would be 2 (because each int occupies 2 bytes) and count would be
100 (because the array contains 100 elements). To obtain the size argument, you can use the sizeof() operator.
The argument fp is, of course, the pointer to type FILE, returned by fopen() when the file was opened. The fwrite() function returns
the number of items written on success; if the value returned is less than count, it means that an error has occurred. To check for
errors, you usually program fwrite() as follows:
if( (fwrite(buf, size, count, fp)) != count)
fprintf(stderr, "Error writing to file.");
Here are some examples of using fwrite(). To write a single type double variable x to a file, use the following:
fwrite(&x, sizeof(double), 1, fp);
To write an array data[] of 50 structures of type address to a file, you have two choices:
fwrite(data, sizeof(address), 50, fp);
fwrite(data, sizeof(data), 1, fp);
The first method writes the array as 50 elements, with each element having the size of a single type address structure. The second
method treats the array as a single element. The two methods accomplish exactly the same thing.
The following section explains fread() and then presents a program demonstrating fread() and fwrite().
The fread() Function
The fread() library function reads a block of data from a binary-mode file into memory. Its prototype in STDIO.H is
int fread(void *buf, int size, int count, FILE *fp);
The argument buf is a pointer to the region of memory that receives the data read from the file. As with fwrite(), the pointer type is
void.
The argument size specifies the size, in bytes, of the individual data items being read, and count specifies the number of items to
read. Note how these arguments parallel the arguments used by fwrite(). Again, the sizeof() operator is typically used to provide the
size argu-ment. The argument fp is (as always) the pointer to type FILE that was returned by fopen() when the file was opened. The
fread() function returns the number of items read; this can be less than count if end-of-file was reached or an error occurred.
Renaming a File
The rename() function changes the name of an existing disk file. The function prototype, in STDIO.H, is as follows:
int rename( const char *oldname, const char *newname );
The filenames pointed to by oldname and newname follow the rules given earlier in this chapter. The only restriction is that both
names must refer to the same disk drive; you can't rename a file to a different disk drive. The function rename() returns 0 on
success, or -1 if an error occurs. Errors can be caused by the following conditions (among others):
The file oldname does not exist.
A file with the name newname already exists.
You try to rename to another disk.
/* Using rename() to change a filename. */
#include <stdio.h> gets(newname);
#include <conio.h>
if ( rename( oldname, newname ) == 0 )
main() printf("%s has been renamed %s.\n", oldname,
{ newname);
char oldname[80], newname[80]; else
clrscr(); fprintf(stderr, "An error has occurred renaming %s.\n",
printf("Enter current filename: "); oldname);
gets(oldname); getch();
printf("Enter new name for file: ");
}
Coping file
#include <stdio.h> }
#include <conio.h> printf("Destination file : ");scanf("%79s",out_name);
void main() if((out_stream=fopen(out_name,"w"))==NULL)
{ {
char in_name[80],out_name[80]; fprintf(stderr,"open of %s for reading failed",out_name);
FILE *in_stream,*out_stream; perror(" because");
int ch; }
clrscr(); while ((ch=fgetc(in_stream))!=EOF)
printf("source file : ");scanf("%79s",in_name); fputc(ch,out_stream);
if((in_stream=fopen(in_name,"r"))==NULL) fclose(in_stream);
{ fclose(out_stream);
fprintf(stderr,"open of %s for reading failed",out_name); getch();
perror(" because"); }
/*Let us C count chars spaces tab and new line in fileprogram perform file I/O in high level unformatted text mode*/
#include<stdio.h> noc++;
#include<conio.h> if(ch==' ')
#define N 4 nob++;
main() if(ch=='\n')
{ nol++;
FILE *fp; if(ch=='\t')
char ch; not++;
int nol=0,not=0,nob=0,noc=0; }
clrscr(); fclose(fp);
fp=fopen("ajay.txt","r"); printf("\nCharacter=%d",noc-nol);
while(1) printf("\nBlank=%d",nob);
{ printf("\nTabs=%d",not);
ch=getc(fp); printf("\nLines=%d",nol);
if(ch==EOF) getch();
break; }
/***/
#include<stdio.h> fp=fopen(fname,"r");
#include<conio.h> while(1)
#include<string.h> {
void main() c=fgetc(fp);
{ if(c==EOF)
FILE *fp; break;
char fname[13]; i= ftell(fp);
char ext[5]=".txt";
char c; }
int i=0,a; fclose(fp);
printf("Enter file name="); printf("Total byte in file = %d\n",i);
gets(fname); getch();
}
strcat(fname,ext);
/*write a program to create a file open it type in some character and count the number of character in file*/
#include<stdio.h> while(strlen(gets(c))>0)
#include<conio.h> {
main() fputs(c,fp);
{ fputs("\n",fp);
FILE *fp,*an; }
int i,count=0; fclose(fp);
char x,c[100]; //open file again to enter text and count number of character
//clrscr(); fp=fopen("new.txt","r");
fp=fopen("new.txt","w");//file has been opened in text mode while(1)
that why Dos will count enter a character {
printf("Enter a any character="); x=fgetc(fp);
if(x==EOF) printf("Number of character you have entered is
break; %d",count);
count++; getch();
} }
fclose(fp);
/*write a program tht will input a person first name, last name, SSB number and age and write the information to a data
file. One person's information should be in a single line. Use the function fprintf to write to the data file. Accept the
information and write the data within a loop. Your program should exit the loop when the word 'EXIT' is entered for the
first name. Remember to close the file termination the program. Use the function strcmp() to compare two strings.*/
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<string.h>
void main()
{
struct emp{
char name[10],last[10];
int ssn,age;
}e[2];
int i;
char x[4]="EXIT";
FILE *fp;
fp=fopen("emp.txt","w");
for(i=0;i<2;i++)
{
printf("Enter EXIT in field name to exit\n");
printf("enter data name,last name, ssn ,age\n");
scanf("%s %s %d
%d",&e[i].name,&e[i].last,&e[i].ssn,&e[i].age);
if(stricmp(x,e[i].name)==0)
exit(0);
else
fwrite(e,sizeof(struct emp),2,fp);
}
fclose(fp);