WHAT IS FILE?
File is a collection of bytes that is stored on secondary storage devices like disk. There are two kinds of files in a system. They are,
1. Text files (ASCII)
2. Binary files
• Text files contain ASCII codes of digits, alphabetic and symbols.
• Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version of text files.
BASIC FILE OPERATIONS IN C PROGRAMMING:
There are 4 basic operations that can be performed on any files in C programming language. They are,
1. Opening a file
2. Closing a file
3. Reading a file
4. Writing in a file
|file open FILE *fp1; fp1=fopen(“filename”, ”‘mode”);||The fopen function is used to open a file. Where, fp1 is file pointer to the data type “FILE”.|
|file close: fclose(fp1);||fclose function closes the file that is being pointed by file pointer fp1.|
|file read: fgets(buffer, size, fp1);||fgets is used to read a file line by line. where, buffer – buffer to put the data in.size – size of the buffer fp1 – file pointer|
|file write: fprintf(fp1, “some data”); fprintf(fp1, “text %d”, variable_name);||fprintf writes the data into a file pointed by fp1.|
MODE OF OPERATIONS PERFORMED ON A FILE IN C LANGUAGE:
There are many modes in opening a file. Based on the mode of file, it can be opened for reading or writing or appending the texts. They are listed below.
• r – Opens a file in read mode and sets pointer to the first character in the file. It returns null if file does not exist.
• w – Opens a file in write mode. It returns null if file could not be opened. If file exists, data are overwritten.
• a – Opens a file in append mode. It returns null if file couldn’t be opened.
• r+ – Opens a file for read and write mode and sets pointer to the first character in the file.
• w+ – opens a file for read and write mode and sets pointer to the first character in the file.
• a+ – Opens a file for read and write mode and sets pointer to the first character in the file. But, it can’t modify existing contents.