用C语言打开文件的几种方式及区别

文件使用方式含义如果指定的文件不存在
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+ 形式打开后,我们可以读写该文件,但是我们读完文件准备写时,文件指针位于文件尾,想要覆盖输入,则必须使用文件定位函数,如fsetposfseekrewind等。
比如从头重新写:则需要fseek(fp, 0, SEEK_SET);将文件指针返回头部。
当从写入切换为读取时,则需要使用fflush清除文件缓存或者使用文件定位函数。

  • 14
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hack Rabbit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值