现在,假设 hello.txt 是硬盘上已有的一个文件,而且内容为 “hello, world” ,在文件的当前指针设置完毕后,我们来介绍 sys_read , sys_write , sys_lseek 如何联合使用才能把数据插入到 hello.txt 中。
可以通过如下方式对它们进行组合应用,应用程序的代码如下:
#include <fcntl.h> #include <stdio.h> #include <string.h> #define LOCATION 6 int main(char argc, char **argv) { char str1[] = "Linux"; char str2[1024]; int fd, size; memset(str2, 0, sizeof(str2)); fd = open("hello.txt", O_RDWR, 0644); lseek(fd, LOCATION, SEEK_SET); strcpy(str2, str1); size = read(fd, str2+5, 6); lseek(fd, LOCATION, SEEK_SET); size = write(fd, str2, strlen(str2)); close(fd); return (0); }
这是一段用户进程的程序,通过这样一段代码就能将 “Linux” 这个字符串插入到 hello.txt 文件中了,最终 hello.txt 文件中的内容应该是 : “hello,Linuxworld” 。
这段代码几乎用到了操作文本文件的所有系统调用,下下面我们来分析一下这些代码的作用。
fd = open("hello.txt", O_RDWR, 0644);
lseek(fd, LOCATION, SEEK_SET);
strcpy(str2, str1);
size = read(fd, str2+5, 6);
lseek(fd, LOCATION, SEEK_SET);
size = write(fd, str2, strlen(str2));
以上所述,就是 read, write, lseek 组合应用,从而实现文件修改的全过程。