调用了write()函数之后,这个进程会关闭打开的文件?

我有一个需要被操作的文件,叫做:save.txt
开始,这个文件里的内容是空的:

clipboard.png

对这个文件执行了如下代码:

#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;
}

得到以下输出:

clipboard.png

也就是只输出了换行,没有输出文件里的内容。但是,执行完了那段代码之后,那个hello字符串已经写进那个save.txt文件里了:

clipboard.png

之后,我在读文件之前,又重新打开了一次文件,就可以读出结果了:

#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;
}

clipboard.png

那么问题来了:在执行完了write函数之后,这个进程会自动关闭这个文件?

阅读 3.7k
1 个回答

这是因为你读和写用的是同一个 fd,写完后文件指针随着移动到末尾了,读的时候从文件尾部自然读不出任何数据了。可以尝试在写完后用 lseek 把文件指针重置一下。

lseek(fd, 0, SEEK_SET);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题