C file read/write operations
C language files
I. Basic file operations:
In C language, operations on data files are performed by file type pointers.
1. FILE type pointer definition: FILE * FILE type variable
2. Call the fopen function to open a file:
File Type pointer variable = fopen (file name, using the file opening method );
File opening methods (12 types)
File Opening Method |
Meaning |
Rt |
Read-only opens a text file and only allows reading data |
Wt |
Only write to open or create a text file, only data can be written |
At |
Append a text file and write data at the end of the file. |
Rb |
Read-only open a binary file and only allow reading data |
Wb |
Only write to open or create a binary file, only data can be written |
AB |
Append a binary file and write data at the end of the file. |
Rt + |
Read and Write |
Wt + |
Read/write to open or create a text file, allowing read/write |
At + |
Open a text file, allow reading, or append data at the end of the file. |
Rb + |
Open a binary file for read and write operations. |
Wb + |
Read/write to open or create a binary file, allowing read and write |
AB + |
Open a binary file, allow reading, or append data at the end of the file. |
3. close the file;
Fclose (File pointer)
Ii. file read/write operations
1. Character read/write functions: fgetc () and fputc ();
2. formatted read/write functions: fscanf () and fprintf ();
3. Data Block read/write functions: fread () and fwrite ();
4. String read/write functions: fgets () and fputs ();
The sample code is as follows:
# Include
# Include
# Include
# Include
# Define NUM 99999 // open or create a FILE * fp; int str [NUM]; void build (int a) {if (a = 1) {if (fp = fopen ("d: // 1234.txt"," w ") = NULL)/* c: \ 123.txt file */{printf ("\ nopen file error"); getchar (); exit (1) ;}} else if (a = 2) {if (fp = fopen ("d: // 1234.txt"," r ") = NULL)/* c: \ 123.txt file */{printf ("\ nopen file error"); getchar (); exit (1) ;}} else if (a = 3) {if (fp = fopen ("d: // 1234", "wb") = NULL)/* Create c: \ 123.txt file */{printf ("\ nopen file error"); getchar (); exit (1) ;}} else if (a = 4) {if (fp = fopen ("d: // 1234", "rb") = NULL)/* Create c: \ 123.txt file */{printf ("\ nopen file error"); getchar (); exit (1) ;}}// Close the file void Close () {fclose (fp) ;}// generate the written data void num () {int I; for (I = 0; I
The result is as follows: