我想像这样将 .txt 文件的内容打印到命令行:
main() {
int fd;
char buffer[1000];
fd = open("testfile.txt", O_RDONLY);
read(fd, buffer, strlen(buffer));
printf("%s\n", buffer);
close(fd);
}
文件 testfile.txt 如下所示:
line1
line2
line3
line4
该函数仅打印前 4 个字母 line
。
当使用 sizeof
而不是 strlen
时,将打印整个文件。
为什么 strlen
不起作用?
最佳答案
在此程序中使用 strlen
根本 是不正确的。在调用 read
之前,缓冲区未初始化并且对其应用 strlen
具有未定义的行为。在调用 read
之后,缓冲区的一些字节数被初始化,但缓冲区不一定是正确的 C 字符串; strlen(buffer)
可能会返回一个与您应该打印出的数据量无关的数字,或者可能仍然有 UB(如果 read
初始化了数组的全长对于非 nul 字节,strlen
将离开末尾)。出于同样的原因,printf("%s\n", buffer)
是错误的。
您的程序也根本无法处理大于缓冲区的文件。
正确的方法是在循环中使用read
和write
的返回值。要告诉 read
缓冲区有多大,您可以使用 sizeof
。 (注意:如果您使用 malloc
分配缓冲区而不是作为局部变量,那么您可以不使用 sizeof
来获取它的大小;你必须自己记住尺寸。)
#include <unistd.h>
#include <stdio.h>
int main(void)
{
char buf[1024];
ssize_t n;
while ((n = read(0, buf, sizeof buf)) > 0)
write(1, buf, n);
if (n < 0) {
perror("read");
return 1;
}
return 0;
}
练习:处理短写和写错误。
关于c - 如何正确地将文件内容打印到 C 中的命令行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43005223/