当前位置:网站首页>文件操作详解(2)
文件操作详解(2)
2022-04-23 16:30:47 【山涧晴岚.】
目录
1.文件的随机读取
1.1 fseek
文件的默认读取是从首元素开始读取的
例如:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE* pf = fopen("test.txt", "r");//以读的方式
if (pf == NULL)
{
perror("fopen");
return 1;
}
char ch = fgetc(pf);//读取一个字符放在ch里,读取后指向的位置会向后偏移
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}
test.txt文件里的内容:
运行结果:
第一个参数为文件指针,第二个参数为偏移量,第三个参数初始的位置 (如下)
SEEK_CUR//文件指针当前的位置
SEEK_END//文件末尾的位置
SEEK_SET//文件开始的位置
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE* pf = fopen("test.txt", "r");//以读的方式
if (pf == NULL)
{
perror("fopen");
return 1;
}
char ch = fgetc(pf);//读取一个字符放在ch里
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
fseek(pf, 2, SEEK_CUR);//从c开始向后偏移2个字符
ch = fgetc(pf);
printf("%c\n", ch);
fseek(pf, 0, SEEK_END);//当前位置的字符为'\0'
ch=fgetc(pf);
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}
运行结果:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE* pf = fopen("test.txt", "w");//以写的方式
if (pf == NULL)
{
perror("fopen");
return 1;
}
fputc('a', pf);
fputc('b', pf);
fputc('c', pf);
fputc('d', pf);
fseek(pf, -3, SEEK_CUR);//当前位置向前偏移3个位置
fputc('e', pf);
fclose(pf);
pf = NULL;
return 0;
}
运行结果:
1.2 ftell
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE* pf = fopen("test.txt", "w");//以写的方式
if (pf == NULL)
{
perror("fopen");
return 1;
}
fputc('a', pf);
fputc('b', pf);
fputc('c', pf);
fputc('d', pf);
fseek(pf, -3, SEEK_CUR);//当前位置向前偏移3个位置
fputc('e', pf);
long pos = ftell(pf);//该函数返回类型为long类型
printf("%ld\n", pos);
fclose(pf);
pf = NULL;
return 0;
}
运行结果:
1.3 rewind

#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE* pf = fopen("test.txt", "w");//以读的方式
if (pf == NULL)
{
perror("fopen");
return 1;
}
fputc('a', pf);
fputc('b', pf);
fputc('c', pf);
fputc('d', pf);
fseek(pf, -3, SEEK_CUR);//当前位置向前偏移3个位置
fputc('e', pf);
long pos = ftell(pf);
printf("%ld\n", pos);
rewind(pf);//返回起始位置
pos = ftell(pf);
printf("%ld\n", pos);
fclose(pf);
pf = NULL;
return 0;
}
运行结果:
2.文本文件和二进制文件
根据数据的组织形式,数据文件被称为 文本文件 或者 二进制文件 。数据在内存中以 二进制 的形式存储,如果不加转换的输出到外存,就是 二进制文件 。如果要求在外存上以 ASCII码 的形式存储,则需要在存储前转换。以 ASCII 字符的形式存储的文件就是 文 本文件
#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;
}
该文件内容为二进制文件
添加到源文件中
右击选择打开方式,以二进制编辑器来打开
里面内容为
因为VS2019以小端存储所以结果为10 27 00 00
3.文件读取结束的判定
在文件读取过程中,不能用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);
}
putchar('\n');
//判断是什么原因结束的
if (ferror(fp))
puts("I/O error when reading");
else if (feof(fp))
puts("End of file reached successfully");
fclose(fp);
}
运行结果:
4.文件缓冲区
ANSIC 标准采用 “ 缓冲文件系统 ” 处理的数据文件的,所谓缓冲文件系统是指系统自动地在内存中为程序中每一个正在使用的文件开辟一块“ 文件缓冲区 ” 。从内存向磁盘输出数据会先送到内存中的缓冲区, 装满 缓冲区后才一起送到磁盘上。如果从磁盘向计算机读入数据,则从磁盘文件中读取数据输入到内存缓冲区( 充满 缓冲区),然后再从缓冲区逐个地将数据送到程序数据区(程序变量等)。缓冲区的大小根据C 编译系统决定的。
例如:
#include <stdio.h>
#include <windows.h>
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;
}
运行结果:
10秒后
结论:因为有缓冲区的存在, C 语言在操作文件的时候,需要做 刷新缓冲区 或者 在文件操作结束的时候关闭文件 。如果不做,可能导致读写文件的问题。
版权声明
本文为[山涧晴岚.]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_62949535/article/details/124234964
边栏推荐
- Sail soft implements a radio button, which can uniformly set the selection status of other radio buttons
- Sail soft calls the method of dynamic parameter transfer and sets parameters in the title
- 欣旺达:HEV和BEV超快充拳头产品大规模出货
- logback的配置文件加载顺序
- Nacos 详解,有点东西
- 漫画:什么是IaaS、PaaS、SaaS?
- 深度学习100例 | 第41天-卷积神经网络(CNN):UrbanSound8K音频分类(语音识别)
- 04 Lua 运算符
- 05 Lua 控制结构
- 【Pygame小游戏】10年前风靡全球的手游《愤怒的小鸟》,是如何霸榜的?经典回归......
猜你喜欢
-
Redis "8" implements distributed current limiting and delay queues
-
G008-hwy-cc-estor-04 Huawei Dorado V6 storage simulator configuration
-
Introduction notes to PHP zero Foundation (13): array related functions
-
Qipengyuan horizon credible meta universe social system meets diversified consumption and social needs
-
Esxi encapsulated network card driver
-
各大框架都在使用的Unsafe类,到底有多神奇?
-
Gartner 发布新兴技术研究:深入洞悉元宇宙
-
Differences between MySQL BTREE index and hash index
-
On the value, breaking and harvest of NFT project
-
文件系统读写性能测试实战
随机推荐
- Gartner 發布新興技術研究:深入洞悉元宇宙
- 阿里研发三面,面试官一套组合拳让我当场懵逼
- 建站常用软件PhpStudy V8.1图文安装教程(Windows版)超详细
- Gartner publie une étude sur les nouvelles technologies: un aperçu du métacosme
- Ali developed three sides, and the interviewer's set of combined punches made me confused on the spot
- File system read and write performance test practice
- Gartner announces emerging technology research: insight into the meta universe
- How magical is the unsafe class used by all major frameworks?
- [pyGame games] how did angry birds, a mobile game that became popular all over the world 10 years ago, dominate the list? Classic return
- 05 Lua control structure
- 04 Lua operator
- 100 deep learning cases | day 41 - convolutional neural network (CNN): urbansound 8K audio classification (speech recognition)
- Cartoon: what are IAAs, PAAS, SaaS?
- Nacos detailed explanation, something
- Loading order of logback configuration file
- Phpstudy V8, a commonly used software for station construction 1 graphic installation tutorial (Windows version) super detailed
- 关于 background-image 渐变gradient()那些事!
- vim编辑器的实时操作
- 磁盘管理与文件系统
- RAID磁盘阵列与RAID5的创建
- LVM与磁盘配额
- Xinwangda: HEV and Bev super fast charging fist products are shipped on a large scale
- 5分钟NLP:Text-To-Text Transfer Transformer (T5)统一的文本到文本任务模型
- 安装及管理程序
- NVIDIA显卡驱动报错
- 人脸识别框架之dlib
- Set the color change of interlaced lines in cells in the sail software and the font becomes larger and red when the number is greater than 100
- Set cell filling and ranking method according to the size of the value in the soft report
- Solution of garbled code on idea console
- Use if else to judge in sail software - use the title condition to judge
- The font of the soft cell changes color
- Take according to the actual situation, classify and summarize once every three levels, and see the figure to know the demand
- Query the data from 2013 to 2021, and only query the data from 2020. The solution to this problem is carried out
- LVM and disk quota
- Creation of RAID disk array and RAID5
- Disk management and file system
- Real time operation of vim editor
- About background image gradient()!
- OMNeT学习之新建工程
- On the security of key passing and digital signature