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:1num:30 ret:1==========++10##3040But instead it completely ignores the overwrite and only moves the file pointer and the output comes out as:num:10 ret:1num:30 ret:1============10203040however if the two lines for the first fscanf and printf are commented, the output becomes:num:20 ret:1============##203040Why?*/#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: 10n20n30n40n for (num = 1; num <= 4; fprintf(fptr, "%dn", num++ * 10)); fclose(fptr); fptr = fopen("data.txt", "r+"); // reopening with r+ // comment the following two lines and overwrite will work! ret = fscanf(fptr, "%dn", &num); printf("num:%d ret:%dn", num, ret); - // overwriting 20 (Fails!, file pointer moves with no error and no output) fprintf(fptr, "##"); fflush(fptr); ret = fscanf(fptr, "%dn", &num); printf("num:%d ret:%dn", 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清除文件缓存或者使用文件定位函数。
免责声明:文章源自网络,版权归原作者所有,如有侵犯联系删除。