You are Here: Home > Computer Subjects > Programming in C Language > …
Explain opening and closing of files with examples.
Ans. A data file allows us to store information permanently and to access and alter that information whenever necessary. There are two types of data files, one is stream-oriented data files and another is system-oriented data files.
When working with a stream – oriented data file, the first step to establish a buffer area, where information is temporarily stored while being transferred between computers memory and the data file. The buffer area is established by writing
FILE * Pointer var;
A data file must then be opened before it can be created and processed. The library function ‘fopen’ is used to open a file. The syntax of fopen is
pintervar = fopen (filename, mode)
A data file opened using fopen must be closed at the end of the program. A library function fclose is used for this purpose.
The syntax for fclose is :
fclose (pointervar);
Example:
void main()
{
FILE *p; char ch;
p=fopen("MyFile.txt","r"); //here option "r" indicates that we opened the file as read mode.
while(1)
{
ch=getc(p);
if(ch==EOF)
break;
else
putc(ch,q);
}
fclose(p);
}
Click Here to Find Latest Jobs and Current Affairs
