我想从标准输入输入文本,然后将其显示在屏幕上,同时对行进行编号。我的程序的最后一部分无法正常工作,我不知道如何正确使用 read()
函数。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <io.h>
#include <string.h>
int main()
{
char s[201];
int i=0, f = open("text.dat", O_RDWR | O_CREAT | O_TRUNC);
while (fgets(s,200,stdin) != NULL)
write(f,s,strlen(s));
char *buf;
while (read(f,buf,200) > 0)
printf("%d %s", i++, *buf);
close(f);
return 0;
}
最佳答案
首先你使用stdin
:
while (fgets(s,200,stdin) != NULL)
write(f,s,strlen(s));
然后您尝试读取文件f
。但是,文件 f
已经位于其末尾,因此第一次调用 read()
返回 0
。因为没有什么可读的。您需要将文件指针移回到文件的开头。
但是基于 read()
的循环仍然不会执行您想要的操作。那是因为您需要面向行的输入。所以你应该使用fgets
而不是read
。就像以面向行的方式处理 stdin
一样,您需要处理对 stdout
的打印。
正如 Mats 指出的,你从未分配过 buf。因此,如果有任何内容需要读取,您将取消引用未初始化的指针。
说了这么多,在我看来,只运行一个循环更有意义。在调用 write()
的循环内调用 printf()
。
while (fgets(s,200,stdin) != NULL)
{
write(f,s,strlen(s));
printf("%d %s", i, s);
i++;
}
关于c - 如何使用 C 中读取的函数显示文件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14043389/