当前位置:网站首页>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边栏推荐
- 要上市的威马,依然给不了百度信心
- I2C子系统之适配器的设备接口分析(i2c-dev.c文件分析)
- 78岁华科教授冲击IPO,丰年资本有望斩获数十倍回报
- Interview summary of large factory Daquan II
- Flask 轻量web框架
- 大厂面试总结大全二
- With the stock price plummeting and the market value shrinking, Naixue launched a virtual stock, which was deeply in dispute
- The money circle boss, who is richer than Li Ka Shing, has just bought a building in Saudi Arabia
- regular expression
- Win32 API 访问路由的加密网页
猜你喜欢

Load test practice of pingcode performance test
![[HCIA continuous update] WLAN overview and basic concepts](/img/50/7eef28b7cfb0a72c97f3c50518ad6d.png)
[HCIA continuous update] WLAN overview and basic concepts

超标量处理器设计 姚永斌 第7章 寄存器重命名 摘录

数学分析_笔记_第7章:多元函数的微分学
![[HCIA continuous update] overview of WLAN workflow](/img/0a/b3986307589a9f7379fe1dd707b9f8.png)
[HCIA continuous update] overview of WLAN workflow

Self reflection of a small VC after two years of entrepreneurship

uni-app与uviewUI实现仿小米商城app(附源码)

TCP两次挥手,你见过吗?那四次握手呢?
![[Huawei HCIA continuous update] SDN and FVC](/img/02/f86b509fdc515f14a4497090f0d070.png)
[Huawei HCIA continuous update] SDN and FVC

“在越南,钱就像躺在街上”
随机推荐
Detectron2 installation method
Face_ Attendance statistics of recognition face recognition
Performance test of Gatling
Once the "king of color TV", he sold pork before delisting
Cann operator: using iterators to efficiently realize tensor data cutting and blocking processing
蓝桥:合根植物
Initial experience of domestic database tidb: simple and easy to use, quick to start
高中物理:力、物体和平衡
uni-app与uviewUI实现仿小米商城app(附源码)
[proteus simulation] printf debugging output example based on VSM serial port
Summary of subsidy policies across the country for dcmm certification in 2022
Pytorch深度学习之环境搭建
New technology releases a small program UNIPRO to meet customers' mobile office scenarios
ARTS_ twenty million two hundred and twenty thousand six hundred and twenty-eight
Solve the El input input box For number number input problem, this method can also be used to replace the problem of removing the arrow after type= "number"
【系统分析师之路】第七章 复盘系统设计(结构化开发方法)
LD_LIBRARY_PATH 环境变量设置
[cloud native] what is the "grid" of service grid?
Master the use of auto analyze in data warehouse
谷粒商城(一)