【发布时间】:2020-01-10 08:19:18
【问题描述】:
我正在使用 linux 在 c 中编写代码并尝试从文件中读取。我已经运行了代码并且它运行良好,但我试图了解使用文件描述符和缓冲区(包括参数)背后的逻辑。请从 r=read(fd,buff,1); 行提供帮助;
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
void main()
{
int fd,r;
char buff[100];
fd=open("test.dat",O_RDONLY);
if (fd==-1)
{
printf("Failed to open and read the file test.dat\n");
exit(1);
}
r=read(fd,buff,1);
while (r>0)
{
printf("%s",buff);
r=read(fd,buff,1);
}
close (fd);
}
【问题讨论】:
-
您确定这可以完美运行吗?因为如果不设置
buff[1] = 0,则无法保证良好的行为 -
仅供参考,这个问题与文件系统几乎没有关系,根本不是 Linux 特定的
-
r 是读取的字节数
-
@MadPhysicist,是的,它有效。我已经运行了
-
The third parameter to
readis the number of bytes requested. 您可以在 Unix(包括 Linux)中获取该信息,方法是使用命令man read显示read的手册页。