Reading From a File
The file read operation in C can be performed using functions fscanf() or fgets(). Both the functions performed the same operations as that of scanf and gets but with an additional parameter, the file pointer. There are also other functions we can use to read from a file. Such functions are listed below:
Function | Description |
---|---|
fscanf() | Use formatted string and variable arguments list to take input from a file. |
fgets() | Input the whole line from the file. |
fgetc() | Reads a single character from the file. |
fgetw() | Reads a number from a file. |
fread() | Reads the specified bytes of data from a binary file. |
So, it depends on you if you want to read the file line by line or character by character.
Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
The getc() and some other file reading functions return EOF (End Of File) when they reach the end of the file while reading. EOF indicates the end of the file and its value is implementation-defined.
Note: One thing to note here is that after reading a particular part of the file, the file pointer will be automatically moved to the end of the last read character.
Basics of File Handling in C
File handing in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program.