【问题标题】:File systems in C in linuxlinux中C语言的文件系统
【发布时间】: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 read is the number of bytes requested. 您可以在 Unix(包括 Linux)中获取该信息,方法是使用命令 man read 显示 read 的手册页。

标签: c linux io posix


【解决方案1】:

基本上,read 返回读取的字节数。在您的代码中,您每次读取 1 个字节并打印它。因此,当它到达文件末尾时,它将停止(因为read 将返回 0)。

您可以在一个read 中读取更多字节。在这种情况下,read 可以返回两个值(当然如果read 成功了):

  1. 您请求的读取字节数(read(fd, buff, 12) 将返回 12)
  2. 如果要读取的字节数少于您请求的字节数(假设您请求了 100,但文件包含 40 个字符),它将返回从文件中读取的字节数,而不是您请求的字节数(即返回 40 , 而不是 100)。

【讨论】:

  • 是的,你说得对。但是当 read 每行遇到一个字符串终止字符('\0')时会发生什么?
  • 好吧,\0 是不可打印的字符,因此您无法看到或将该字符写入文件。此外,在每一行的末尾,有\n 字符,而不是\0。甚至,如果您读取数据,则不止一行,\n 将在您的字符串内。因此,阅读后,您的缓冲区可以包含:“Hello World\nNew Line”
猜你喜欢
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
相关资源
最近更新 更多