In this tutorial, you will learn about file handling in C. You will learn how to read from a file, write to a file. close a file and more.
File pointers: It is not enough to just display the data on the screen. We need to save it because memory is volatile and its contents would be lost once the program terminated, so if we need some data again there are two ways, one is retyped via keyboard to assign it to a particular variable, and the other is regenerate it via programmatically both options are tedious.
At such times it becomes necessary to store the data in a manner that can be later retrieved and displayed either in part or in whole. This medium is usually a “file” on the disk.
Introduction to file
Until now we have been using the functions such as scanf, printf, getch, putch, etc to read and write data on the variables and arrays for storing data inside the programs But this approach poses the following problems.
- The data is lost when program terminated or variable goes out of scope.
- Difficulty to use large volume of data.
We can overcome these problems by storing data on secondary devices such as Hard Disk. The data is stored on the devices using the concept of “file”. A file is a collection of related records, a record is composed of several fields and a field is a group of characters. The most straightforward use of files is via a file pointer.
We need to declare the pointer first in a program and is done in the following ways:
1 2 | FILE *fp; //fp <strong>is</strong> a pointer to a file. |
The type FILE is not a basic type, instead, it is defined in the header file stdio.h, this file must be included in your program
Types of Files
Basically there are two types of file:
- Text files: These files are .txt files that contain the plain text when you open it and easy to edit and delete. You can create such files with text editors such as Notepad.
- Binary file: These are the .bin files present in the computer. They store the data in a binary form such as in 0’s and 1s instead of plain text. Although it is harder to understand, it gives better security than plain text files.
File Operation
- Create a new file (fopen with attributes as “a” or “a+” or “w” or “w++”).
- Open an existing file (fopen).
- Read from file (fscanf or fgets).
- Write to a file (fprintf or fputs).
- Moving a specific location in a file(Seeking) (fseek, rewind).
- Closing File (fclose).
Opening a file:
fopen() is used to open a file by giving two values such as file_name and mode to which you want to open the file. The various modes are stated below.
1 2 | FILE *fp; fp = fopen ("file_name", "mode"); |
There are various modes to open a file. Check the table given below.
File Modes | Description |
---|---|
r | read |
w | write, overwrite file if it exists |
a | write, but append instead of overwrite |
w+ | read & write, do not destroy file if it exists |
a+ | read & write, but append instead of overwrite |
b+ | may be appended to any of the above to force the file to be opened in binary mode rather than text mode. |
Sequential file access is performed with the following library functions:
- fopen() – Create a new file
- fclose() – Close file
- getc() – Read character from file
- putc() – Write a character to a file
- getw() – Read Integer from file
- putw() – Write Integer to a file
- fprintf() – Write set of data values
- fscanf() – read set of data values
Closing a file:
fclose() function is used to close the file once the operation on file is done. And it is done in a flowing way:
1 | int fclose( FILE *fp ); |
Example on how to use open and close mode.
1 2 3 4 5 6 | //Opens inputs.txt file in read mode FILE *fp; fp=fopen("input.txt","r"); //closing inputs.txt file fclose(fp); //close file |
Reading from a file:
Reading operation are performed fgetc(), fgets() and fscanf(). You can use them according to your choice. If you want to read character by character then you may use fgetc() or for line by line, you can use fgets().
The end of the file is denoted by EOF(end of file) ot NULL character (\0) value at the end. It tells the function that it has reached the end of the file.
1 2 3 | FILE * fp; fp = fopen(“fileName.txt”, “r”); fscanf(fp, "%s %s %s %d", str1, str2, str3, &year); |
Writing to a file:
Writing operation in a file can be performed with the use of fprintf, fputc and fputs.
- fputc(char, file_pointer): It writes a character to the file.
- fputs(str, file_pointer): It writes a string to the file..
- fprintf(file_pointer, str, variable_lists): The first value is the file_pointer that points to the String that needs to be printed.
1 2 3 | FILE *fp; fp= fopen(“file_Name.txt”, “w”); fprintf(fp, "%s %s %s %d", "This", "is", "new", 2021); |
Example of Writing and closing a file in C programming.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include < stdio.h > #include <string.h > int main() { //file pointer FILE * fp; // Get the data to be written in file char writeData[50] = "Simple2Code: Learn Coding"; //opening file in a write mode fp = fopen("TestFile.txt", "w"); //Check for the null if (fp == NULL) { printf("TestFile.txt failed to open."); } else { printf("Successfully Opened.\n"); if (strlen(writeData) > 0) { //writing in the file using fputs() fputs(writeData, fp); fputs("\n", fp); } //Closing the file fclose(fp); printf("The file is now closed."); } return 0; |