When data is stored using variables, the data is lost when the program exits unless something is done to save it. C views file simply as a sequential stream of bytes. Each file ends either with an end-of-file marker or at a specified byte number recorded in a system maintained, administrative data structure. C supports two types of files called binary files and text files.
The difference between these two files is in terms of storage. In text files, everything is stored in terms of text i.e. even if we store an integer 54; it will be stored as a 3-byte string – “54�”.
A binary file contains data that was written in the same format used to store internally in main memory. For example, the integer value 1245 will be stored in 2 bytes depending on the machine while it will require 5 bytes in a text file.
When the file is opened the stream is associated with the file. Three streams are opened bydefault with program execution:
- standard input: enables program to read data from keyboard
- standard output: enables program to write data on screen
- standard error: enables program to track input and output errors
The above streams are manipulated with the help of pointers called stdin, stdout and stderr.
Further, to access any file, we need to declare a pointer to FILE structure (defined in stdio.h) and then associate it with a particular file. This pointer is referred to as file pointer and is declared as:
FILE *fp;
Opening a file using function fopen()
Once the file pointer has been declared, the next step is to open a file. The fopen() function opens a stream and links a file with the stream. This function returns a file pointer.
Syntax:
FILE *fopen(char *filename,mode);
Different modes for opening a file:
MODE MEANING
r/rt opens a text file for read only access
w/wt opens a text file for write only access
r+t opens a text file for read and write access
w+t creates a text file for read and write access
/*program that tries to open a file*/
#include
void main()
{
FILE *fp;
fp=fopen(“file1.txt”,”r”);
if(fp==NULL)
printf(“FILE DOES NOT EXISTS”);
}
Closing a file using fclose()
The file that has been opened should be closed before exiting the program.
syntax:
int fclose(FILE *fptr);
the return value is 0 if the file successfully closed or EOF if an error occurred. If the fclose() function is not called the operating system normally close the file when the program execution terminates.