- 1 文件操作
- 1.1 open
- 1.2 read
- 1.3 write
- 1.4 close
- 1.5 lseek
- 1.6 stat
- 1.7 示例
- 1.8 实现cp命令
- 2 从【用户态】到【 内核态】
1 文件操作
C语言:fopen, fread, fwrite, fclose, fseek(库函数)
- 系统调用函数:调用在用户态,执行在内核态
- 查看帮助文档
#查看帮助文档 man 1 命令 man 2 系统调用函数 man 3 库函数1.1 open
#include1.2 read#include #include int open(const char* filename, int flag, int mode); //返回值:<0,错误 // >=0,文件描述符,fd //flg打开方式:读:O_RDONLY // 写:O_WRONLY // 读写:O_RDWR // 追加:O_APPEND // 创建(没有该文件时):O_CREAT //mode创建爱你文件时,指定权限:0nnn
#include1.3 writeint read(int fd, void* buf, size_t count); //fd:读取的文件,由open返回值指定 //buf:指定读取数据的存储位置,起始地址 //count:指定一次读取的最大字节数(一般为缓冲区大小) //返回值:-1,错误 // 读取数据的字节数
#include1.4 closeint write(int fd, void* buf, size_t count); //fd:读取的文件,由open返回值指定 //buf:指定写入数据的存储位置,起始地址 //count:指定写入数据的字节数 //返回值:-1,错误 // 写入数据的字节数
#include1.5 lseekint close(int fd); //fd:指定文件 //返回值:-1,错误 // 0,成功
#include1.6 stat#include off_t lseek(int fd, off_t offset, int whence); //fd:指定文件,由open返回值指定 //offset:移动读写偏移量 //whence: SEEK_SET:文件开始位置 // SEEK_CUR:当前位置 // SEEK_END:文件末尾位置 //返回值:-1,错误 // 当前读写文件位置,距离开始地址的字节数
#include1.7 示例#include #include //获取文件属性信息 int stat(const char *pathname, struct stat *statbuf); int fstat(int fd, struct stat *statbuf); int lstat(const char *pathname, struct stat *statbuf);
1 #include1.8 实现cp命令2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 9 int main() 10 { //读写方式打开或者创建,读写读写读权限 11 int fd = open("./a.txt",O_RDWR | O_CREAT, 0664); 12 13 char buf[128] = "hello world"; 14 15 write(fd,buf, strlen(buf));//从buf写入到文件 16 17 char readbuf[128] = {}; 18 19 lseek(fd, 0, SEEK_SET);//移动读写偏移量设置为0 20 21 read(fd, readbuf, 127);//读取文件数据到readbuf 22 23 printf("%sn", readbuf); 24 25 close(fd);//关闭文件 26 27 exit(0); 28 }
1 #include2 从【用户态】到【 内核态】2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 9 int main(int argc, char* argv[]) 10 { 11 int fdr = open(argv[1], O_RDONLY);//输入的main函数的第二个参数,作为源文件 12 13 int fdw = open(argv[2], O_WRonLY | O_CREAT, 0664);//输入的main函数的第三个参数,作为要拷贝的目标文件 14 15 while(1)//每次从fdr读取127个字节,然后写入fdw中,直到读取为空 16 { 17 char buf[128] = {}; 18 19 int n = read(fdr, buf, 127); 20 if(n==0) 21 { 22 break; 23 } 24 25 write(fdw, buf, n); 26 } 27 close(fdr); 28 close(fdw); 29 30 exit(0); 31 }
——>用户态调用
——>触发0x80中断
——>保存程序上下文
——>将系统调用函数的调用号保存到eax寄存器中
——>执行中断处理程序(内核中)
——>通过调用号查找系统调用表执行内核中的函数并将返回值保存到eax寄存器中
——>返回系统调用函数的返回值



