Declare file pointer for opening or closing a file as FILE *fp.
You can use multiple variables to access different files in a program by declaring as – FILE *fp1,*fp2,*fp3 ;
Function fopen() is used to open the file for reading or writing operation which requires filename to open as the first argument and file mode as the second argument as – fp=fopen(“myfile.dat”, “filemode”);
File name is the name of the file that you need to open for read or write.
File mode indicates for what purpose file is to be opened i.e. for read, write.
Different modes of file open are:
pic
pic
pic
File Open
The file open function fopen() serves two purposes:
It makes the connection between the physical file and the stream.
It creates “a program file structure to store the information” C needs to process the file.
Syntax:
filepointer=fopen(“filename”, “mode”);
The file mode tells C how the program will use the file.
The filename indicates the system name and location for the file.
We assign the return value of fopen to our pointer variable: spData = fopen(“MYFILE.TXT”, “w”); spData = fopen(“A:\\MYFILE.TXT”, “w”);
pic
Closing a File
When we finish with a mode, we need to close the file before ending the program or
beginning another mode with that same file.
After closing the file, the connection between file and program is broken. Hence, operations like read, write can't be done.
On closing the file, all the buffers associated with it are written to the file.
Although all the files are closed automatically when the program terminates, sometimes it may be necessary to close the file using fclose() function.
To close a file, we use fclose() and the pointer variable as : fclose(spData);
– Here spData is pointer variable