关于文件读写操作

xiaoxiao2025-07-24  37

朱老师嵌入式核心课程笔记 文件读写操作

文件读写操作代码段

#include<stdio.h> //使用man查询得出文件读写API所需要的头文件 //man 1 xx查linux shell命令,man 2 xxx查API, man 3 xxx查库函数 #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<string.h> #include <unistd.h> int main() { int fd = -1; //file description 文件描述符 int ret = 0; char buf[100] = {0}; char writebuf[20] = "hello man"; //打开文件 fd = open("a.txt", O_RDWR); if(-1 == fd) //也可以写成if(fd < 0),打开正确,则返回一个新的文件描述符,否则返回-1 { printf("open error\n"); } else { printf("open a.txt successful, fd = %d\n",fd); } //读写文件 //写文件 ret = write(fd, writebuf, strlen(writebuf)); if(-1 == ret) { printf("write error\n"); } else { printf("write successfully, ret = %d\n", ret); printf("[%s]\n", writebuf); } //读文件 ret = read(fd, buf, 20); if(-1 == ret) { printf("read error\n"); } else { printf("read successfully, ret = %d\n", ret); printf("读取内容是:[%s]\n", buf); } //ssize_t write(int fd, const void * buf, size_t count); //ssize_t read(int fd, void * buf, size_t count); //ssize_t类型是typedef重定义的一个类型,其实就是int //关闭文件 close(fd); return fd; }

关于文件读写操作涉及的API

read #include <unistd.h>

ssize_t read(int fd, void *buf, size_t count);

write #include <unistd.h>

ssize_t write(int fd, const void *buf, size_t count);

open #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>

int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); int creat(const char *pathname, mode_t mode);

close #include <unistd.h>

int close(int fd);

Ⅰ. errno 和 perror ① errno,错误号码,对各种错误做编号,当函数执行错误时,函数返回特定编号告知错误; ② errno,由OS维护的一个全局变量; ③ errno,本质是一个int类型的数字,由数字对应错误; ④ perror,为使数字对应相应错误,Linux提供一个函数perror(printf error), perror函数内部读取error并且将相应数字对应的错误打印显示; ⑤ perror,可借用该函数得出错误原因,perror(" XXX 错误 “); 代替 printf(” XXX错误 ");

Ⅱ. 文件I/O和标准I/O ① 文件I/O,open,close,read,write等API函数构成的一套用来读写文件的体系,效率不够高; ② 标准I/O,应用层c语言库封装的文件读写函数(fopen,fclose,fread,fwrite),在应用层添加了一个buf,fwrite写入的内容不会直接存入内核buf中,而是进入应用层标准I/O库中的buf,根据OS单次count来选择好的时机来完成write到内核中的buf,再根据硬盘特性来选择时机写入到硬盘中。

转载请注明原文地址: https://www.6miu.com/read-5033635.html

最新回复(0)