【发布时间】:2019-01-28 18:00:20
【问题描述】:
当我尝试从文件中读取数据并打印时,printf 将一个空字符串打印到终端。
使用:Ubuntu 16.04。
gcc 版本 5.4.0。
内核:4.15.0-43-generic
试过了:
写入数据后添加fsync调用。
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#define SIZE 6
int main()
{
int ret = -1;
char buffer[SIZE] = { 0 };
int fd = open("data.txt", O_CREAT | O_RDWR, 0666);
if (fd < 0)
{
perror("open()");
goto Exit;
}
if (write(fd, "Hello", 5) < 0)
{
perror("write()");
goto Exit;
}
fsync(fd);
if (read(fd, buffer, SIZE - 1) < 0)
{
perror("read()");
goto Exit;
}
printf("%s\n", buffer);
ret = 0;
Exit:
close(fd);
return ret;
}
预期:应该在文件中写入和读取数据。
实际: 数据写入文件。读取数据后,printf 打印一个空字符串。
【问题讨论】:
-
您的错误检查已损坏。你不知道
read是否成功。 -
@EugeneSh。
buffer初始化为零。