Summary of file operations in c language

1. Meaning:

Stored on the external memory, compared to constants, variables, data, etc., are all stored on the internal memory.

The keyboard is the input file stdin;

The display is the output file stdout;

Writing a file, we understand it as output, from memory to external storage; such as printf, fprintf, fputc, fputs, fwrite;

Reading files, we understand as input, from external storage to memory; such as scanf, fscanf, fgetc, fgets, fread;

2. Classification:

1) According to the access method:

Sequential access: read and write operations always start from the beginning of the file;

Random access: Read and write operations can be performed from anywhere in the file.

2) According to the form of access:

Text file: Each character is stored in the form of ASCII code value; fixed-length decoding code, but the file can be recognized.

Binary file: Store the data in the form of storage in the memory (binary code); variable-length decoding and encoding, but the file is not identifiable.

E.g:

3.14. In text files, each number is stored as a character, and one character occupies one byte;//After opening the file, what you see is what you get;

If it is stored as a binary file, if the float type is used, it occupies 4 bytes, and if it is double, it occupies 8 bytes. //After opening the file, it is garbled;

But if both the text file and the binary file store the contents of the character array, open the binary file and you will see the corresponding hexadecimal number.

3. File pointer

#include <stdio.h>

typedef struct{
    short level; //缓冲区满或空 程度
    unsigned flags;//文件状态标志
    char fd; //文件描述符
    unsigned char hold;// 如无缓冲区不读取字符
    char filename[20];//文件名
    char path[30];//文件路径
}FILE;

 FILE* fp;

4. Open the file

Before reading and writing the file, you need to open the file:

FILE* fp = fopen(文件名,文件的打开方式);

例如:
FILE* fp = fopen("test.txt","r");
FILE* fp = fopen("\\nand_flash\\test.txt","r");\\用两个/表示一个\

若文件无法打开,会返回NULL。
故:
FILE* fp;
if((fp = fopen("test.txt","r"))==NULL)
{
    printf("fopen file fail\n");
    exit;
}

 

Open method meaning Open method meaning
“r” Read only, open a text file, the file must exist “r+” Read and write, open text file, the file must exist
“w” Write only, open a text file, the file does not need to exist, if it exists, the content will be cleared when fopen “w+” Can read and write, create and open a new text file, the file does not need to exist, if it exists, the content will be cleared when fopen
“a” Append to write, the file may not exist, add from the end of the text file “a+” Can read and write, open a text file, the file may not exist, add at the end of the file
"rb" Read only, open a binary file, the file must exist "rb+" Read and write, open a binary file, the file must exist
“wb” Write only, open the binary file, the file does not need to exist, if it exists, the content will be cleared “wb+” Read and write, create and open a new binary file, the file may not exist, if it exists, the content will be cleared
"ab" Append, the file may not exist, add from the end of the binary file "ab+" Read and write, open a binary file, the file may not exist, add at the end of the file

Comparison of r and r+: both need to create a file first; r+ adds the writable function, that is: open the file once, you can write to the file, read the file; when writing, it is written at the position of the file location pointer, which will overwrite the pointer The content behind. Write a few bytes to cover a few bytes.

      Write advantages of r+: 1) It will not clear all the contents of the original file, and write the contents by changing the file position pointer through the fseek() function (write a few, overwrite a few). 2) When reading and writing files, you only need to open the file once.

Comparison of w and w+: Both have no requirements for the existence of files. If the file exists, the original file will be deleted when fopen, and a new file will be created; w+ adds the read function, that is: after writing the file, pass fseek To change the file position pointer, you can also read out the contents of the file,

      Note that w+ cannot read first and then write, because after using fopen, it is an empty file.

Comparison of r and w: The r file must exist; the w file can exist or not, if it exists, the content in the original file will be overwritten ( when fopen, the original file is deleted and a file with the same name is regenerated ), If it does not exist, this file will be created.

      The advantage of w is to regenerate a new file and overwrite the original file.

Comparison of r+ and w+ : Both can be read and written; r+ requires the existence of the file, w+ does not require the existence of the file, if it exists, it will delete and create a new file (that is, use the w+ attribute, regardless of whether the file exists, Will be recreated);

r+ can write first and then read, or read first and then write (because the file already exists, and there is content in it), w+ can only write first and then read, because after fopen, the file is a newly created file is empty, so it can only be written first Read later.

Comparison of w and a: Both do not require the existence of the file; w will delete the file and create a new file regardless of whether the file exists or not; for a, if the file is not created, the same as w, if the file is created, it will be Continue to write content at the end of the file.

Comparison of a and a+: Both do not require the existence of the file, and neither can change the original content of the file; a can only be added at the end, and the file position pointer is invalid (that is, fseek is invalid); a+ can only be written at the end, file position The pointer is only valid for reading (write operation will move the file pointer to the end of the file)

5. Close the file 

After the file is read and written, it should be closed to prevent data loss;

The essence of closing a file is to release the file pointer so that the file pointer variable no longer points to the file.

fclose(fp);
//关闭成功返回0;
//关闭失败返回非0

6. Reading and writing of files

6.1 fscanf and fprintf //read and write text files , the data format is arbitrary

Memory: The format and meaning of fscanf and fprintf and scanf and printf are basically the same;

scanf, is from the keyboard (stdin file) read takes a value and assignment to a variable; // fscanf also read values from the file, assign a variable

   scanf("%d",&m) is equivalent to fscanf(stdin,"%d",&m);

printf, is to write the value of a variable to the display (stdout file ); //fprintf also writes a variable to a file;

   printf("%d",n); is equivalent to fprintf(stdout,"%d",n);

1)fprintf(文件指针,格式字符串,输出项表)
例如:
fprintf(fp,"%d",m);//将变量m以%d的形式写到fp指向的文件中

2)fscanf(文件指针,格式字符串,输入项表)
例如:
fscanf(fp,"%d",&n);//注意取地址符号&//将fp所指的文件以%d的形式读取到变量n中

6.2 fputc (putc) and fgetc (getc) // read and write characters from text files

fputc(ch,fp);//ch可以是字符常量,可以是字符变量,写入到fp所指的文件中
putchar(ch);等价于fputc(ch,stdout);

ch = fgetc(fp);//从fp所指的文件中读取字符作为返回值赋给字符型变量ch
ch = getchar();等价于ch = getc(stdin);

6.3 fputs and fgets function // from a text file read and write character string

fputs(str,fp);//str是待写入文件的字符串的首地址
//注意:字符串最后的\0不会写入文件,也不会自动加'\n';
写入成功,函数值为非0,否则为0;

fgets(str,n,fp);//str是存放字符串的起始地址;n是int型变量
//从fp所指的文件中读n-1个字符依次放入到以str为旗帜地址的内存中,读入结束后,自动在最后加'\n',并以str作为函数值返回。
//注意:调用该函数时,最多只能读取n-1个字符。要为'\0'保留一个字符的空间

 6.4 fwrite and fread// read and write data in binary files

fwrite(buffer,size,count,fp);
//buffer为指针,代表内存中一段存储空间的首地址;
size,代表每单元的字节数;
count代表要进行读写的单元数
//将以buffer为其实地址的内存中的count个单元,每个单元size个字节写到fp所指的文件中。

int a[4]={1,2,3,4}; fwrite(a,2,4,fp);
//将以a为起始地址的内存中的4个单元,每单元2个字节写(输出)到fp所指的文件中。

fread(buffer,size,count,fp);
//buffer是指针,代表内存中存储空间的地址;
count代表进行读写的单元数;
size带包每单元的字节数;
//从fp所指的文件中读(输入)count个单元,每个单元size个字节,到以buffer为起始地址的内存中。

int  a[4];
fread(a,2,4,fp);
//从fp所指的we年中读4个单元,每个单元2个字节,到以a为起始地址的内存中。

7. Determine whether the file is over

1) feof(fp); Judge whether the file is over ------ f end of file//You can judge binary files or text files

End of file: the return value is 1;

The file is not over, the return value is 0;

2) EOF;//Text file

Because the text files are all ASCII code, 0-255, it is impossible to be -1, so use EOF as the end mark of the text file.

8. File positioning function

After the file is fopened, the file position pointer points to the beginning of the file, before the first data;//Note that it is the file position pointer, not the file pointer

After the file is fclosed, the file position pointer points to the end of the file, after the last data.

After the data is read, the file location pointer points to before the data has not been read, that is, the data after the pointer is read.

When the data is written, the true value of the file position points to just after the data is written.

We use the fseek function to change the position pointer of the file.

Starting point name Representative number
File start position SEEK_SET 0
File current location SEEK_CUR 1
End of file SEEK_END 2
fseek(fp,offset,origin);//一般用于二进制文件
offset是以origin为基点,以字节为单位的位移量,当offset为正整数,表示位置指针从指定位置向后移动,当offset为负整数,表示位置指针从指定位置向前移动,为长整型。

fseek(fp,30L,SEEK_SET);//位置指针从开始位置向后移30个字节。
fseek(fp,-10*sizeof(int),SEEK_END);//位置指针从文件尾部位置向前移10*sizeof(int)个字节。

fseek(fp,0L,SEEK_SET);//位置指针移动到开始位置。
fseek(fp,0L,SEEK_END);//位置指针移动到末尾位置。

 

 

long t = ftell(fp);
//返回当前位置指针据文件开头的字节数

//该函数可以用来获取文件的大小
fseek(fp,0L,SEEK_END);
long t = ftell(fp);

 

rewind(fp);//无返回值
//使文件位置指针返回到文件开头位置,等价于 fseek(fp,0L,SEEK_SET);

9. Summary

1) The operations on files in the c language all start with f.

2) r+, w+, a+, in fact, can be realized by multiple operations of r, w, a and fseek functions.

 

Guess you like

Origin blog.csdn.net/modi000/article/details/113096605