当前位置:网站首页>fopen、fread、fwrite、fseek 的文件处理示例
fopen、fread、fwrite、fseek 的文件处理示例
2022-07-04 16:32:00 【华为云】
与任何操作系统一样,文件处理是 Linux 中的核心概念。任何系统程序员都会将其作为他/她的初始编程任务之一来学习。编程的这一方面涉及系统文件。
通过文件处理,可以对系统文件进行创建、修改、删除等操作。在本文中,尝试引入非常基础的文件处理。
文件处理功能
在本文中,我们将介绍以下文件处理中常用的函数:
fopen()
FILE *fopen(const char *path, const char *mode);
fopen() 函数用于打开文件并将 I/O 流与其关联。这个函数有两个参数。第一个参数是指向包含要打开的文件名的字符串的指针,而第二个参数是要打开文件的模式。模式可以是:
- 'r' : 打开文本文件进行阅读。流位于文件的开头。
- 'r+' : 打开读写。流位于文件的开头。
- 'w' :将文件截断为零长度或创建文本文件以进行写入。流位于文件的开头。
- 'w+' : 打开读写。如果文件不存在,则创建该文件,否则将其截断。流位于文件的开头。
- 'a' :打开以进行附加(在文件末尾写入)。如果文件不存在,则创建该文件。流位于文件的末尾。
- 'a+' :打开以供读取和附加(在文件末尾写入)。如果文件不存在,则创建该文件。读取的初始文件位置在文件的开头,但输出始终附加到文件的末尾。
fopen() 函数在成功时返回 FILE 流指针,而在失败时返回 NULL。
fread() 和 fwrite()
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
fread/fwrite 函数用于从 fopen 函数打开的文件中读取/写入数据。这些函数接受三个参数。第一个参数是指向用于读取/写入数据的缓冲区的指针。读取/写入的数据采用“nmemb”元素的形式,每个“size”字节长。
如果成功,fread/fwrite 返回从 fopen 函数打开的流中实际读取/写入的字节数。如果失败,则返回较少数量的字节(然后请求读/写)。
fseek()
int fseek(FILE *stream, long offset, int wherece);
fseek() 函数用于将流的文件位置指示器设置为新位置。该函数接受三个参数。第一个参数是 fopen() 函数返回的 FILE 流指针。第二个参数 'offset' 告诉我们要查找的字节数。第三个参数“whence”告诉从哪里寻找“offset”字节数。wherece 的可用值是 SEEK_SET、SEEK_CUR 或 SEEK_END。这三个值(按顺序)描述了文件的开头、当前位置和文件的结尾。
成功时,此函数返回 0,否则返回 -1。
fclose()
int fclose(FILE *fp);
fclose() 函数首先刷新 fopen() 打开的流,然后关闭底层描述符。成功完成后,此函数返回 0,否则返回文件结尾 (eof)。在失败的情况下,如果进一步访问流,则行为保持未定义。
代码
#include<stdio.h>#include<string.h>#define SIZE 1#define NUMELEM 5int main(void){ FILE* fd = NULL; char buff[100]; memset(buff,0,sizeof(buff)); fd = fopen("test.txt","rw+"); if(NULL == fd) { printf("\n fopen() Error!!!\n"); return 1; } printf("\n File opened successfully through fopen()\n"); if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd)) { printf("\n fread() failed\n"); return 1; } printf("\n Some bytes successfully read through fread()\n"); printf("\n The bytes read are [%s]\n",buff); if(0 != fseek(fd,11,SEEK_CUR)) { printf("\n fseek() failed\n"); return 1; } printf("\n fseek() successful\n"); if(SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd)) { printf("\n fwrite() failed\n"); return 1; } printf("\n fwrite() successful, data written to text file\n"); fclose(fd); printf("\n File stream closed through fclose()\n"); return 0;}
上面的代码假设您有一个测试文件“test.txt”放置在运行该可执行文件的相同位置。
最初文件中的内容是:
$ cat test.txthello everybody
现在,运行代码:
$ ./fileHandling File opened successfully through fopen() Some bytes successfully read through fread() The bytes read are [hello] fseek() successful fwrite() successful, data written to text file File stream closed through fclose()
再次检查文件 test.txt 的内容。如下所示,文件的内容已被修改。
$ cat test.txthello everybodyhello
边栏推荐
- 上市公司改名,科学还是玄学?
- 创业两年,一家小VC的自我反思
- I always thought that excel and PPT could only be used for making statements until I saw this set of templates (attached)
- Interview summary of large factory Daquan II
- "In Vietnam, money is like lying on the street"
- Weima, which is going to be listed, still can't give Baidu confidence
- [daily question] 871 Minimum refueling times
- Redis主从复制
- 【Hot100】31. 下一个排列
- Self reflection of a small VC after two years of entrepreneurship
猜你喜欢
Tutorial on the use of Huawei cloud modelarts (with detailed illustrations)
90后开始攒钱植发,又一个IPO来了
为啥有些线上演唱会总是怪怪的?
DB engines database ranking in July 2022: Microsoft SQL Server rose sharply, Oracle fell sharply
【HCIA持续更新】网络管理与运维
Why are some online concerts always weird?
The controversial line of energy replenishment: will fast charging lead to reunification?
[HCIA continuous update] overview of WLAN workflow
我写了一份初学者的学习实践教程!
TCP waves twice, have you seen it? What about four handshakes?
随机推荐
国产数据库TiDB初体验:简单易用,快速上手
MySQL常用增删改查操作(CRUD)
78 year old professor Huake impacts the IPO, and Fengnian capital is expected to reap dozens of times the return
Load test practice of pingcode performance test
People in the workplace with a miserable expression
Analysis of I2C adapter driver of s5pv210 chip (i2c-s3c2410. C)
I wrote a learning and practice tutorial for beginners!
Imitation of numpy 2
2022年全国CMMI认证补贴政策|昌旭咨询
Redis master-slave replication
Why are some online concerts always weird?
Oppo Xiaobu launched Obert, a large pre training model, and promoted to the top of kgclue
股价大跌、市值缩水,奈雪推出虚拟股票,深陷擦边球争议
[Huawei HCIA continuous update] SDN and FVC
You should know something about ci/cd
无心剑中译伊丽莎白·毕肖普《一门技艺》
补能的争议路线:快充会走向大一统吗?
New technology releases a small program UNIPRO to meet customers' mobile office scenarios
【Hot100】31. Next spread
ITSS运维能力成熟度分级详解|一文搞清ITSS证书