当前位置:网站首页>【C语言进阶】文件操作(二)
【C语言进阶】文件操作(二)
2022-08-01 23:09:00 【沐曦希】
大家好我是沐曦希
1.前言
前面学到了文件的打开和关闭,以及文件顺序读写的函数。那么现在来学习文件的随机读写函数等知识。
2.文件的随机读写
2.1 fseek函数
int fseek ( FILE * stream, long int offset, int origin );

根据文件指针的位置和偏移量来定位文件指针。
例如:
#include <stdio.h>
int main()
{
FILE* pFile = fopen("example.txt", "wb");
fputs("This is an apple.", pFile);
fseek(pFile, 9, SEEK_SET);
fputs(" sam", pFile);
fclose(pFile);
return 0;
}

2.2 ftell函数
long int ftell ( FILE * stream );

返回文件指针相对于起始位置的偏移量

2.3 rewind
void rewind ( FILE * stream );

让文件指针的位置回到文件的起始位置
例如:
#include <stdio.h>
int main()
{
int n = 0;
char buffer[27] = {
'\0' };
FILE* pFile = fopen("myfile.txt", "w+");
for (n = 'A'; n <= 'Z'; n++)
fputc(n, pFile);
rewind(pFile);
fread(buffer, 1, 26, pFile);
fclose(pFile);
buffer[26] = '\0';
puts(buffer);
return 0;
}

3.文本文件和二进制文件
根据数据的组织形式,数据文件被称为文本文件或者二进制文件。
数据在内存中以二进制的形式存储,如果不加转换的输出到外存,就是二进制文件。
如果要求在外存上以ASCII码的形式存储,则需要在存储前转换。以ASCII字符的形式存储的文件就是文本文件。
一个数据在内存中是怎么存储的呢?
字符一律以ASCII形式存储,数值型数据既可以用ASCII形式存储,也可以使用二进制形式存储。
如有整数10000,如果以ASCII码的形式输出到磁盘,则磁盘中占用5个字节(每个字符一个字节),而二进制形式输出,则在磁盘上只占4个字节(VS2013测试)。
#include <stdio.h>
int main()
{
int a = 10000;
FILE* pf = fopen("test.txt", "wb");
fwrite(&a, 4, 1, pf);//二进制的形式写到文件中
fclose(pf);
pf = NULL;
return 0;
}



4.文件读取结束的判定
4.1 被错误使用的feof
牢记:在文件读取过程中,不能用feof函数的返回值直接用来判断文件的是否结束.
而是应用于当文件读取结束的时候,判断是读取失败结束,还是遇到文件尾结束。
1.文本文件读取是否结束,判断返回值是否为 EOF ( fgetc ),或者 NULL ( fgets )
例如:
fgetc 判断是否为 EOF.
fgets 判断返回值是否为 NULL。
2.二进制文件的读取结束判断,判断返回值是否小于实际要读的个数。
例如:
fread判断返回值是否小于实际要读的个数。
正确的使用:
文本文件的例子:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int c; // 注意:int,非char,要求处理EOF
FILE* fp = fopen("test.txt", "r");
if (!fp) {
perror("File opening failed");
return EXIT_FAILURE;
}
//fgetc 当读取失败的时候或者遇到文件结束的时候,都会返回EOF
while ((c = fgetc(fp)) != EOF) // 标准C I/O读取文件循环
{
putchar(c);
}
//判断是什么原因结束的
if (ferror(fp))
puts("I/O error when reading");
else if (feof(fp))
puts("End of file reached successfully");
fclose(fp);
}

二进制文件的例子:
#include <stdio.h>
enum
{
SIZE = 5
};
int main(void)
{
double a[SIZE] = {
1.,2.,3.,4.,5. };
FILE* fp = fopen("test.bin", "wb"); // 必须用二进制模式
fwrite(a, sizeof * a, SIZE, fp); // 写 double 的数组
fclose(fp);
double b[SIZE];
fp = fopen("test.bin", "rb");
size_t ret_code = fread(b, sizeof * b, SIZE, fp); // 读 double 的数组
if (ret_code == SIZE)
{
puts("Array read successfully, contents: ");
for (int n = 0; n < SIZE; ++n)
printf("%f ", b[n]);
putchar('\n');
}
else {
// error handling
if (feof(fp))
printf("Error reading test.bin: unexpected end of file\n");
else if (ferror(fp))
{
perror("Error reading test.bin");
}
}
fclose(fp);
fp = NULL;
return 0;
}

5.文件缓冲区
ANSIC 标准采用“缓冲文件系统”处理的数据文件的,所谓缓冲文件系统是指系统自动地在内存中为程序中每一个正在使用的文件开辟一块“文件缓冲区”。从内存向磁盘输出数据会先送到内存中的缓冲区,装满缓冲区后才一起送到磁盘上。如果从磁盘向计算机读入数据,则从磁盘文件中读取数据输入到内存缓冲区(充满缓冲区),然后再从缓冲区逐个地将数据送到程序数据区(程序变量等)。缓冲区的大小根据C编译系统决定的。

#include <stdio.h>
#include <stdio.h>
#include <windows.h>
//VS2019 WIN11环境测试
int main()
{
FILE* pf = fopen("test.txt", "w");
fputs("abcdef", pf);//先将代码放在输出缓冲区
printf("睡眠10秒-已经写数据了,打开test.txt文件,发现文件没有内容\n");
Sleep(10000);
printf("刷新缓冲区\n");
fflush(pf);//刷新缓冲区时,才将输出缓冲区的数据写到文件(磁盘)
//注:fflush 在高版本的VS上不能使用了
printf("再睡眠10秒-此时,再次打开test.txt文件,文件有内容了\n");
Sleep(10000);
fclose(pf);
//注:fclose在关闭文件的时候,也会刷新缓冲区
pf = NULL;
return 0;
}


这里可以得出一个结论:
因为有缓冲区的存在,C语言在操作文件的时候,需要做刷新缓冲区或者在文件操作结束的时候关闭文件。
如果不做,可能导致读写文件的问题。
6.写在最后
那么文件操作到这里就结束。
边栏推荐
- SQL29 Calculate the average next day retention rate of users
- Graph Theory - Strongly Connected Component Condensation + Topological Sort
- (Translation) How the contrasting color of the button guides the user's actions
- Ten years after graduation, financial freedom: those things that are more important than hard work, no one will ever teach you
- Check if point is inside rectangle
- Create virtual environments with virtualenv and Virtualenvwrapper virtual environment management tools
- qt-faststart 安装使用
- Solve the port to take up
- 【好书推荐】第一本无人驾驶技术书
- 萍不回答
猜你喜欢

移动端人脸风格化技术的应用

D - Linear Probing- 并查集

From 0 to 100: Notes on the Development of Enrollment Registration Mini Programs

测试岗月薪5-9k,如何实现涨薪到25k?

JS prototype hasOwnProperty in Add method Prototype end point Inherit Override parent class method

npm包【详解】(内含npm包的开发、发布、安装、更新、搜索、卸载、查看、版本号更新规则、package.json详解等)

chrome copies the base64 data of an image

小程序毕设作品之微信美食菜谱小程序毕业设计成品(5)任务书

小程序毕设作品之微信美食菜谱小程序毕业设计成品(6)开题答辩PPT

编曲软件FL studio20.8中文版功能和作用
随机推荐
Deep learning Course2 first week Practical aspects of Deep Learning exercises
excel clear format
npm npm
数据库表设计规则
1391D. 505 状压dp
Chapter 12 End-User Task As Shell Scripts
程序员如何优雅地解决线上问题?
Calculate the midpoint between two points
下载安装 vscode(含汉化、插件的推荐和安装)
Wechat Gymnasium Appointment Mini Program Graduation Design Finished Work (4) Opening Report
解决yolov5训练时出现:“AssertionError: train: No labels in VOCData/dataSet_path/train.cache. Can not train ”
E - Integer Sequence Fair
D - Linear Probing- 并查集
From 0 to 1: Design and R&D Notes of Graphic Voting Mini Program
CF1705D Mark and Lightbulbs
【SeaTunnel】从一个数据集成组件演化成企业级的服务
perspectiveTransform warpPerspective getPerspectiveTransform findHomography
PDF转Word有那么难吗?做一个文件转换器,都解决了
联邦学习在金融领域的发展和应用
C#大型互联网平台管理框架源码:基于ASP.NET MVC+EF6+Bootstrap开发,支持多数据库