无法使用系统调用 read 读取文本文件的最后一行

标签 c system call

我正在使用 C 中的简单代码(逐个字符)读取此文本文件:

This is the file

printf 函数不会打印任何内容!

这只是一行文本(但它发生在文本文件的最后一行)。

这是代码:

int main(int argc, char *argv[])
{
    int fd, bytes_read;
    char buf;

    if((fd = open(argv[1], O_RDONLY)) == -1)
    {
        perror("open");
        exit(EXIT_FAILURE);
    }

    do
    {
        if((bytes_read = read(fd, &buf, sizeof(buf))) == -1)
        {
           perror("read");
           exit(EXIT_FAILURE);
        }

        printf("%c", buf);
    }
    while(bytes_read != 0);

    close(fd);
}

谢谢!

最佳答案

我不确定这是否是原因,但这可能是因为“非空的源文件应以换行符结尾,该字符前面不应紧接着反斜杠字符。”

参见http://robots.thoughtbot.com/no-newline-at-end-of-file/要了解更多信息,这是一本有趣的读物。

关于无法使用系统调用 read 读取文本文件的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20585386/

相关文章:

c - 在 C 中分配的指针上 malloc 安全吗?

c - Malloc 与自定义分配器 : Malloc has a lot of overhead. 为什么?

php - 构造函数后直接调用函数 : new Object()->callFunction()

c# - 完成对 SerialPort.ReadLine() 的调用

android - 如何检测未接听的来电挂断。?

Java CAS 操作比 C 等效操作执行得更快,为什么?

C、fork()中的一些语句没有执行

java - System.out.println 和 System.err.println 乱序

java - 限制一个java命令的线程数

c++ - write 返回较小尺寸时该怎么办?