我有一个需要被操作的文件,叫做:save.txt
开始,这个文件里的内容是空的:
对这个文件执行了如下代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int fd, len = 10, ret;
char* buf = "hello";
char save[255];
fd = open ("save.txt", O_RDWR);
ret = write(fd, buf, strlen(buf));
read(fd, save, 100);
printf("%s\n", save);
return 0;
}
得到以下输出:
也就是只输出了换行,没有输出文件里的内容。但是,执行完了那段代码之后,那个hello
字符串已经写进那个save.txt
文件里了:
之后,我在读文件之前,又重新打开了一次文件,就可以读出结果了:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int fd, len = 10, ret;
char* buf = "hello";
char save[255];
fd = open ("save.txt", O_RDWR);
ret = write(fd, buf, strlen(buf));
fd = open ("save.txt", O_RDWR);
read(fd, save, 100);
printf("%s\n", save);
return 0;
}
那么问题来了:在执行完了write
函数之后,这个进程会自动关闭这个文件?
这是因为你读和写用的是同一个 fd,写完后文件指针随着移动到末尾了,读的时候从文件尾部自然读不出任何数据了。可以尝试在写完后用 lseek 把文件指针重置一下。