English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to handle files in C. You will learn to use fprintf(), fscanf(), fread(), fwrite(), fseek(), and other standard I/O.
Files are containers used in computer storage devices to store data.
All data will be lost when the program terminates. Even if the program terminates, the data stored in the file will be retained.
If you need to enter a large amount of data, it will take a lot of time to enter all of it.
However, if you have a file containing all the data, you can easily access the content of the file using some command methods in C.
You can easily move data from one computer to another without any changes.
When processing files, you should understand two types of files:
text files
binary files
Text files are common.txtfiles. You can easily create text files with any simple text editor (such as Notepad).
When you open these files, you will see all the content in plain text. You can easily edit or delete content.
They are easy to read with minimal maintenance, provide the least security, and occupy more storage space.
Binary files are mainly used in.binfiles.
They do not store data in plain text format, but in binary format (0 and1) to store data.
Compared to text files, they can hold more data, are not easy to read, and provide better security.
In C, you can perform four main operations on files:
create a new file
open an existing file
Close the file
Read information and write information to a file
When processing a file, you need to declare a file type pointer. This declaration is necessary for communication between the file and the program.
FILE *fptr;
Use the fopen() function defined in the stdio.h header file to open a file.
In standard I / The syntax for opening a file in C is:
ptr = fopen("fileopen","mode");
For example,
fopen("E:\\cprogram\\newprogram.txt","w"); fopen("E:\\cprogram\\oldprogram.bin","rb");
Suppose the file newprogram.txt does not exist at the path E:\cprogram. The first function creates a new file named newprogram.txt and opens it according to'w'The mode opens the file for writing.
Write mode allows you to create and edit (overwrite) the content of the file.
Now, suppose the second binary file oldprogram.bin exists at the path E:\cprogram. The second function opens an existing file in binary mode'rb'Read.
Read mode allows you to read the file and does not allow you to write to the file.
Mode | The meaning of the mode | During the absence of the file |
---|---|---|
r | OnlyReadModeOpen. | If the file does not exist, fopen() returns NULL. |
rb | Open in binary mode for reading. | If the file does not exist, fopen() returns NULL. |
w | Open a text file, allowing write access to the file. | Open a text file, allowing write access to the file. If the file does not exist, a new file will be created. Here, your program will write content from the beginning of the file. If the file exists, it will be truncated to zero length and rewritten. |
wb | Open the file in binary mode for writing. | If the file exists, its content will be overwritten. If the file does not exist, it will be created. |
a | Open for appending. Data is added to the end of the file. | If the file does not exist, it will be created. |
ab | Open in binary mode for appending. Data is added to the end of the file. | If the file does not exist, it will be created. |
r+ | Open for reading and writing. | If the file does not exist, fopen() returns NULL. |
rb+ | Open in binary mode for reading and writing. | If the file does not exist, fopen() returns NULL. |
w+ | Open a text file, allowing read and write access to the file | If the file exists, its content will be overwritten. If the file does not exist, it will be created. |
wb+ | Open in binary mode for reading and writing. | If the file exists, its content will be overwritten. If the file does not exist, it will be created. |
a+ | Open in read and append mode. | If the file does not exist, it will be created. |
ab+ | Open in binary mode for reading and appending. | If the file does not exist, it will be created. |
Read/After writing, the file should be closed (both text files and binary files).
The fclose() function can close the file.
fclose(fptr);
Here, fptr is the file pointer associated with the file to be closed.
To read and write text files, we use the fprintf() and fscanf() functions.
They are just the file versions of printf() and scanf(). The only difference is that fprint() and fscanf() require a pointer to the structure FILE.
#include <stdio.h> #include <stdlib.h> int main() { int num; FILE *fptr; // If you are using MacOS or Linux, please use the correct path fptr = fopen("C:\\program.txt","w"); if(fptr == NULL) { printf("Error!"); exit(1); } printf("Enter num: "); scanf("%d",&num); fprintf(fptr,"%d",num); fclose(fptr); return 0; }
This program takes a number from the user and stores it in the file program.txt.
After compiling and running the program, you can see the text file program.txt created on the C drive of the computer. When opening the file, you can see the input integer.
#include <stdio.h> #include <stdlib.h> int main() { int num; FILE *fptr; if ((fptr = fopen("C:\\program.txt","r")) == NULL){ printf("Error! opening file"); //If the file pointer returns NULL, the program exits. exit(1); } fscanf(fptr,"%d", &num); printf("Value of n=%d", num); fclose(fptr); return 0; }
This program reads the integer existing in the program.txt file and prints it to the screen.
If you read fromExample1The file has been successfully created, running this program will provide you with the input integer.
Other functions, such as fgetchar(), fputc(), etc., can be used in a similar manner.
In the case of binary files, fread() and fwrite() functions are used to read from and write to files on the disk, respectively.
To write to a binary file, you need to use the fwrite() function. These functions take four parameters:
The address of the data to be written to the disk
The size of the data to be written to the disk
The number of such data
The pointer to the file to be written to.
fwrite(addressData, sizeData, numbersData, pointerToFile);
#include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\\program.bin","wb")) == NULL){ printf("Error! opening file"); // If the file pointer returns NULL, the program exits. exit(1); } for(n = 1; n < 5; ++n); { num.n1 = n; num.n2 = 5*n; num.n3 = 5*n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } fclose(fptr); return 0; }
In this program, we create a new file program.bin on the C drive.
We declare three numbers n1, n2and n3The structure threeNum, and define it as num in the main function.
Now, in the for loop, we use fwrite() to store the value in the file.
The first parameter accepts the address of num, and the second parameter accepts the size of the structure threeNum.
Since we only insert an instance of num, the third parameter is1The last parameter* fptr points to the file where we want to store the data.
Finally, we close the file.
The fread() function also adopts a syntax similar to the above fwrite() function.4parameters.
fread(addressData, sizeData, numbersData, pointerToFile);
#include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\\program.bin","rb")) == NULL){ printf("Error! opening file"); //If the file pointer returns NULL, the program exits. exit(1); } for(n = 1; n < 5; ++n); { fread(&num, sizeof(struct threeNum), 1, fptr); printf("\n"1: %d\t\n2: %d\t\n3: %d\", num.n1, num.n2, num.n3); } fclose(fptr); return 0; }
In this program, you read the same file program.bin and browse the records one by one in a loop.
In simple terms, you will be reading from* A threeNum of size threeNum from the file fptr points to*Read a threeNum of size threeNum from the file pointed to by fptr into the num structure.
You will get the sameExample3inInsert records with the same record.
If there are many records in the file and specific records need to be accessed, it is necessary to traverse all records to obtain the record.
This will waste a lot of memory and operation time. Using fseek() can easily obtain the required data.
As the name implies, fseek() positions the cursor at the given record in the file.
fseek(FILE * stream, long int offset, int whence);
The first parameter stream is a pointer to the file. The second parameter is the position of the record to be searched, and the third parameter specifies the position to start the offset.
Position | Meaning |
---|---|
SEEK_SET | Offset from the beginning of the file. |
SEEK_END | Offset from the end of the file. |
SEEK_CUR | Offset from the current position of the cursor in the file. |
#include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\\program.bin","rb")) == NULL){ printf("Error! opening file"); //If the file pointer returns NULL, the program exits. exit(1); } // Move the cursor to the end of the file. fseek(fptr, -sizeof(struct threeNum), SEEK_END); for(n = 1; n < 5; ++n); { fread(&num, sizeof(struct threeNum), 1, fptr); printf("\n"1: %d\t\n2: %d\t\n3: %d\n", num.n1, num.n2, num.n3); fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR); } fclose(fptr); return 0; }
This program will start reading records from the file program.bin in reverse order (from last to first) and print them.