文件使用方式 | 含义 | 如果指定的文件不存在 |
---|---|---|
r(只读) | 读取一个已经存在的文本文件 | 出错 |
w(只写) | 打开一个文本文件,输出数据,若文件存在则文件长度清为0,即该文件内容会消失 | 建立新文件 |
a (追加) | 向文本文件末尾添加数据,原来文件中的数据保留,新的数据添加到文件为,原文件EOF保留 | 建立新文件 |
rb(只读) | 读取一个二进制文件 | 出错 |
wb(只写) | 打开一个二进制文件,输出数据,若文件存在则文件长度清为0,即该文件内容会消失 | 建立新文件 |
ab (追加) | 向二进制文件尾添加数据 | 建立新文件 |
r+ (读写) | 对一个文本文件进行读写操作 | 出错 |
w+ (读写) | 对一个文本文件进行读写操作,若文件存在则文件长度清为0,即该文件内容会消失 | 建立新文件 |
a+(读写) | 向文本文件末尾添加数据,原来文件中的数据保留,新的数据添加到文件尾,原文件EOF不保留 | 建立新文件 |
rb+ (读写) | 读写一个二进制文件 | 出错 |
wb+ (读写) | 对一个二进制文件进行读写操作,若文件存在则文件长度清为0,即该文件内容会消失 | 建立新文件 |
ab+(读写) | 向二进制文件末尾添加数据,原来文件中的数据保留,新的数据添加到文件尾 | 建立新文件 |
r+具有读写属性,从文件头开始写,保留原文件中没有被覆盖的内容;
w+也具有读写属性,写的时候如果文件存在,会被清空,从头开始写。
先读后写先写后读的问题
再用C语言对文件先读后写或者先写后读时,一定要注意文件指针的位置情况。不然可能导致本该重写的以追加方式写入等错误。
e.g.
The output of the follwing code is supposed to be: (and it is with gcc on linux)
num:10 ret:1
num:30 ret:1
==========++
10
##
30
40
But instead it completely ignores the overwrite and only moves the file
pointer and the output comes out as:
num:10 ret:1
num:30 ret:1
============
10
20
30
40
however if the two lines for the first fscanf and printf
are commented, the output becomes:
num:20 ret:1
============
##
20
30
40
Why?
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
FILE* fptr;
int num,ret, ch;
fptr = fopen("data.txt", "w"); // creating data.txt file: 10\n20\n30\n40\n
for (num = 1; num <= 4; fprintf(fptr, "%d\n", num++ * 10));
fclose(fptr);
fptr = fopen("data.txt", "r+"); // reopening with r+
// comment the following two lines and overwrite will work!
ret = fscanf(fptr, "%d\n", &num);
printf("num:%d ret:%d\n", num, ret); -
// overwriting 20 (Fails!, file pointer moves with no error and no output)
fprintf(fptr, "##");
fflush(fptr);
ret = fscanf(fptr, "%d\n", &num);
printf("num:%d ret:%d\n", num, ret);
fclose(fptr);
fptr = fopen("data.txt", "r"); // reopening with r
printf("============\n");
while ((ch = fgetc(fptr)) != EOF) putchar(ch); // printing the content of data.txt
fclose(fptr);
return 0;
}
当文件以r+
, w+
, 或者 a+
形式打开后,我们可以读写该文件,但是我们读完文件准备写时,文件指针位于文件尾,想要覆盖输入,则必须使用文件定位函数,如fsetpos
,fseek
和rewind
等。
比如从头重新写:则需要fseek(fp, 0, SEEK_SET);
将文件指针返回头部。
当从写入切换为读取时,则需要使用fflush
清除文件缓存或者使用文件定位函数。