首页 > 编程知识 正文

c语言打开文件的使用方式,c语言可以打开什么格式文件

时间:2023-05-04 14:09:16 阅读:286671 作者:4648

文件使用方式含义如果指定的文件不存在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: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清除文件缓存或者使用文件定位函数。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。