Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

C File read and write


May 11, 2021 C


Table of contents


C The file reads and writes

In this chapter we'll show you how A programmers create, open, close, or close text files or bin files.

A file, whether it is a text file or a binary file, represents a series of bytes. T he C language not only provides access to top-level functions, but also provides underlying (OS) calls to process files on storage devices. This chapter explains the important calls to file management.

Open the file

You can use the fopen() function to create a new file or to open an existing file, a call that initializes an object of type FILE that contains all the necessary information to control the flow. Here's a prototype of this function call:

FILE *fopen( const char * filename, const char * mode );

Here, filename is a string used to name a file, and the value of the access mode mode can be one of the following values:

model describe
r Open an existing text file that allows you to read files.
w Open a text file, allow writing to 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.
a Open a text file to write a file in additional mode.If the file does not exist, a new file will be created.Here, your program adds content in existing file content.
r+ Open a text file to allow reading and writing.
w+ Open a text file to allow reading and writing.If the file already exists, the file will be truncated to zero length. If the file does not exist, a new file will be created.
a+ Open a text file to allow reading and writing.If the file does not exist, a new file will be created.Read will start from the beginning of the file, and write can only be added mode.

If you are working with binary files, you need to replace the above access mode with the following access mode:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Close the file

In order to close the file, use the fclose() function. The prototype of the function is as follows:

 int fclose( FILE *fp );

If the file is successfully closed, the fclose() function returns zero, and if an error occurs when the file is closed, the function returns EOF. T his function actually emptys the data in the buffer, closes the file, and frees up all memory used for the file. EOF is a constant defined in the header file stdio.h.

The C standard library provides a variety of functions to read and write files by character or as a fixed-length string.

Write to the file

Here are the simplest functions for writing characters to a stream:

int fputc( int c, FILE *fp );

The function fputc() writes the character value of argument c to the output stream to which fp points. I f the write is successful, it returns the written character, and if an error occurs, EOF is returned. You can use the following function to write a string that ends with null into the stream:

int fputs( const char *s, FILE *fp );

The function fputs() writes the string s to the output stream to which fp points. I f the write succeeds, it returns a non-negative value and, if an error occurs, EOF. Y ou can also write a string to a file using the int fprintf (FILE sfp, const char s format, ...) function. Try the following example:

Note: Make sure that you have a /tmp directory available, and if it doesn't exist, you'll need to create it first on your computer.

#include <stdio.h>

int main()
{
   FILE *fp;

   fp = fopen("./tmp/test.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
}

When the above code is compiled and executed, it creates a new file test .txt in the /tmp directory and writes two lines using two different functions. Let's read this file next.

Read the file

Here are the simplest functions for reading a single character from a file:

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file that fp points to. T he return value is a read character, and if an error occurs, an EOF is returned. The following function allows you to read a string from the stream:

char *fgets( char *buf, int n, FILE *fp );

The function fgets() reads n - 1 character from the input stream to which fp points. It copies the read string to the buffer buf and ends the string by appending an null character at the end.

If the function encounters a line break ''n' or the end EOF of the file before reading the last character, only the read characters, including line breaks, are returned. You can also use the int fscanf (FILE sfp, const char s format, ...) function to read strings from a file, but it stops reading when the first space character is encountered.

Binary I/O function

The following two functions are used for binary inputs and outputs:

size_t fread(void *ptr, size_t size_of_elements, 
             size_t number_of_elements, FILE *a_file);
              
size_t fwrite(const void *ptr, size_t size_of_elements, 
             size_t number_of_elements, FILE *a_file);

Both functions are used for reading and writing blocks - usually arrays or structures.


Instance:

The file opens the output with:

 1 #include <stdio.h>
 2  
 3 int main()
 4 {
 5    FILE *fp = NULL;
 6  
 7    fp = fopen("/tmp/test.txt", "w+"); //第一个逗号前是文件位置。逗号之后是打开文件方式
 8    fprintf(fp, "This is testing for fprintf...\n");  //逗号之前是一个指针,表明往里面输入。逗号之后fprintf是往文件里面输入
 9    fputs("This is testing for fputs...\n", fp);
10    fclose(fp);  //记得用完关闭文件
11 }

File open read:

 1 #include <stdio.h>
 2  
 3 int main()
 4 {
 5    FILE *fp = NULL;
 6    char buff[255];
 7  
 8    fp = fopen("/tmp/test.txt", "r");
 9    fscanf(fp, "%s", buff);  //写入的时候和平常没有区别,还是只有字符串变量前不加‘&’,其他int、double等类型前都要加‘&’符号
10    printf("1: %s\n", buff );
11  
12    fgets(buff, 255, (FILE*)fp);  //scanf遇到空格就会断开,gets会读取空格,遇到换行就结束
13    printf("2: %s\n", buff );     //255是限制最大读取内容长度
14    
15    fgets(buff, 255, (FILE*)fp);   
16    printf("3: %s\n", buff );
17    fclose(fp);
18  
19 }

File read and write:

The file determines whether to end with thefeof() function

 1 #include <stdio.h>
 2 int main()
 3 {
 4    FILE *fp = NULL;
 5    double buff;
 6    double s;
 7    int w;
 8    scanf("%lf",&s);
 9    w=s;
10    fp = fopen("coursese.txt", "w");
11    fprintf(fp,"%lf %lf %d",s,s,w);  //这个%d后面不能加'\n',因为在文件中虽然一行什么东西都没有但是这一行确实存在,那么就不会
12    fclose(fp);                      //遇到文件结束标志。不仅换行不能交,空格也不能交
13    //即fprintf(fp,"%lf %lf %d ",s,s,w);、fprintf(fp,"%lf %lf %d ",s,s,w);  这两种形式都错
14    fp = fopen("coursese.txt", "r");
15    while(1){
16         if(feof(fp)) break;  
17         fscanf(fp, "%lf%lf%d", &buff,&s,&w);
18         printf("%lf %lf %d\n",buff,s,w);
19    }
20    fclose(fp);
21 }

Plus %s can also:

 1 #include <stdio.h>
 2 int main()
 3 {
 4    FILE *fp = NULL;
 5    double buff;
 6    double s;
 7    int w;
 8    char ss[55];
 9    scanf("%lf",&s);
10    scanf("%s",ss);
11    w=s;
12    fp = fopen("coursese.txt", "w");
13    fprintf(fp,"%lf %lf %d %s",s,s,w,ss);  //这个%d后面不能加'\n',因为在文件中虽然一行什么东西都没有但是这一行确实存在,那么就不会
14    fclose(fp);                      //遇到文件结束标志。不仅换行不能交,空格也不能交
15    //即fprintf(fp,"%lf %lf %d ",s,s,w);、fprintf(fp,"%lf %lf %d ",s,s,w);  这两种形式都错
16    fp = fopen("coursese.txt", "r");
17    while(1){
18         if(feof(fp)) break;
19         fscanf(fp, "%lf%lf%d%s", &buff,&s,&w,ss);
20         printf("%lf %lf %d %s\n",buff,s,w,ss);
21    }
22    fclose(fp);
23 }

There is another way to judge the end of a file: fgetc()

But this function is equivalent to getchar(), which draws a character from the file so that the file pointer moves one bit back, causing the data to be taken out differently than when it comes in

Code:

 1 #include <stdio.h>
 2 int main()
 3 {
 4    FILE *fp = NULL;
 5    double buff;
 6    double s;
 7    int w;
 8    char ss[55];
 9    scanf("%lf",&s);
10    scanf("%s",ss);
11    w=s;
12    fp = fopen("coursese.txt", "w");
13    fprintf(fp,"%lf %lf %d %s",s,s,w,ss);
14    fclose(fp);
15    fp = fopen("coursese.txt", "r");
16 
17    char ch;
18    while(1){
19         ch=fgetc(fp);  
20         if(ch==EOF) break;
21         fscanf(fp, "%lf%lf%d%s", &buff,&s,&w,ss);
22         printf("%lf %lf %d %s\n",buff,s,w,ss);
23    }
24    fclose(fp);
25 }

Given the way it judges the file, we can enter an extra space in front of each data to act as a useless character absorbed by that fgetc

Code:

 1 #include <stdio.h>
 2 int main()
 3 {
 4    FILE *fp = NULL;
 5    double buff;
 6    double s;
 7    int w;
 8    char ss[55];
 9    scanf("%lf",&s);
10    scanf("%s",ss);
11    w=s;
12    fp = fopen("coursese.txt", "w");
13    fprintf(fp," %lf %lf %d %s",s,s,w,ss);  //前面多加了一个空格。也可以加其他
14    fclose(fp);
15    fp = fopen("coursese.txt", "r");
16 
17    char ch;
18    while(1){
19         ch=fgetc(fp);
20         if(ch==EOF) break;
21         fscanf(fp, "%lf%lf%d%s", &buff,&s,&w,ss);
22         printf("%lf %lf %d %s\n",buff,s,w,ss);
23    }
24    fclose(fp);
25 }