当前位置:网站首页>文件操作下(C语言)
文件操作下(C语言)
2022-07-22 00:10:00 【旧梦拾遗186】
作者:旧梦拾遗186
相关链接:文件操作上(C语言)
每日励志:
人的潜能是无限的,努力一把,才知自己真正的实力。因为树的方向,风决定。人的方向,自己决定。
前言:
今天小编带大家来学习c语言文件的操作。
目录
一.文件的随机读写
1.1fseek
根据文件指针的位置和偏移量来定位文件指针。
例子:
#include<stdio.h> int main() { FILE* p; p = fopen("test.txt","r"); if (p == NULL) { perror("File opening failed"); } fputs("hello world", p); fseek(p,6, SEEK_SET); int c = fgetc(p); printf("%c\n", c); c = fgetc(p); printf("%c", c); fclose(p); p = NULL; return 0; }
#include<stdio.h> int main() { FILE* p; p = fopen("test.txt","r"); if (p == NULL) { perror("File opening failed"); } fputs("hello world", p); fseek(p,6, SEEK_SET); int c = fgetc(p); printf("%c\n", c); c = fgetc(p); printf("%c\n", c); fseek(p, 1, SEEK_CUR); c = fgetc(p); printf("%c", c); fclose(p); p = NULL; return 0; }
1.2ftell
返回文件指针相对于起始位置的偏移量
例子:
#include<stdio.h> int main() { FILE* p; p = fopen("test.txt","r"); if (p == NULL) { perror("File opening failed"); } fputs("hello world", p); fseek(p,6, SEEK_SET); int c = fgetc(p); printf("%c\n", c); c = fgetc(p); printf("%c\n", c); fseek(p, 1, SEEK_CUR); c = fgetc(p); printf("%c\n", c); int b=ftell(p); printf("%d", b); fclose(p); p = NULL; return 0; }
1.3rewind
让文件指针的位置回到文件的起始位置
#include <stdio.h> int main() { int n; FILE* pFile; char buffer[27]; 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; }
二. 文本文件和二进制文件
根据数据的组织形式,数据文件被称为文本文件或者二进制文件。数据在内存中以二进制的形式存储,如果不加转换的输出到外存,就是二进制文件。如果要求在外存上以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; }
三.文件读取结束的判定
牢记:在文件读取过程中,不能用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);
}
四.文件缓冲区
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; }
因为有缓冲区的存在,C语言在操作文件的时候,需要做刷新缓冲区或者在文件操作结束的时候关闭文
件。如果不做,可能导致读写文件的问题。
结语:
每个人的成长都是能力和想要得到的东西,不断匹配的过程,当你的才华和欲望不匹配时,你就该静下心来学习了,如果小编的总结能对你有所帮助,希望小伙伴们三连加关注哦,你的支持是小编创作的最大动力。
边栏推荐
- Interview reply 4
- Rare earth Developers Conference | streamnational Zhai Jia and Liu Dezhi share the road of cloud native technology transformation
- Microservice practice | centralized configuration center config symmetric encryption practice
- c语言进阶篇:数据的存储(浮点型)
- Use of split function in MATLAB
- Window compilation generates Darknet (cuda11.1+opencv4.5+vs2019)
- Talk about how programmers improve their writing ability
- 并发内存模型之AQS——ReentrantLock加锁流程
- [ManageEngine] seven ways to strengthen the security of enterprise privileged access
- NVIDIA programmable inference accelerator tensorrt learning notes (I) -- start
猜你喜欢
简易消息队列实现 Nodejs + Redis =MQ
Pads Sketchpad box
PyTorch(四)——PyTorch模型定义
Apachecon Asia 2022 opens registration: pulsar technology issues make a big debut
Pytorch(三)——FashionMNIST时装分类
NVIDIA programmable inference accelerator tensorrt learning notes (I) -- start
MySQL调优(D)
2. Overview of information collection
c语言分层理解(c语言分支和循环语句)
Alternative addition and the number of schemes of square walking
随机推荐
Is it safe for Huatai Securities to open an account and open online banking? Do you need to go to the sales department
Interview 3 (multiple processes call the same dynamic library)
基于 ABP 实现 DDD-- 领域服务、应用服务和 DTO 实践
如果想和开发少battle,那你一定要懂数据库
Window compilation generates Darknet (cuda11.1+opencv4.5+vs2019)
How to set the screen not to turn off after locking the screen in win10
【C】 General template of information management system / address book (introduce static, dynamic and file versions)
Research on autojs wechat: many tests have found that occasionally click() returned true, but it did not click successfully, such as "address book" (solved)
Idea decompiles the entire jar package source code
torch.jit.trace与torch.jit.script的区别
生信常用分析图形绘制 -- 各种类型的热图!你学会了吗?
If you want to develop less battle, you must understand the database
Interview reply 4
c语言分层理解(c语言分支和循环语句)
There are two key skills for high availability of microservices, which you must use
《天幕红尘》笔记与思考(二)你知道别人的认识和你自己知道
Capacitive touch chip used in touch panel
PADS画板框
JUC-同步
Rare earth Developers Conference | streamnational Zhai Jia and Liu Dezhi share the road of cloud native technology transformation