我想从stdin输入文本,然后在屏幕上显示它,同时对行进行编号。我的程序的最后一部分不起作用,我不知道如何正确使用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;
}
答案 0 :(得分:2)
首先,您消耗stdin
:
while (fgets(s,200,stdin) != NULL)
write(f,s,strlen(s));
然后您尝试从文件f
中读取。但是,文件f
已经结束,因此第一次调用read()
会返回0
。因为没有什么可读的。您需要将文件指针移回文件的开头。
但是基于read()
的循环仍然无法执行您想要的操作。那是因为你想要面向行的输入。因此,您应该使用fgets
而不是read
。与您以面向行的方式处理stdin
的方式相同,您需要将打印处理到stdout
。
正如Mats指出的那样,你从未分配过buf。因此,如果有任何要阅读的内容,您将取消引用未初始化的指针。
说完所有这些之后,在我看来只运行一个循环就更有意义了。在调用printf()
的循环内调用write()
。
while (fgets(s,200,stdin) != NULL)
{
write(f,s,strlen(s));
printf("%d %s", i, s);
i++;
}
答案 1 :(得分:0)
奇怪的输出:我原以为这部分会崩溃得很厉害:
char *buf;
while (read(f,buf,200) > 0)
printf("%d %s", i++, *buf);
buf没有被初始化为任何东西,因此指向“那边”(“无处有用”的总体方向)。这可能会导致Linux / Unix系统中出现SIGSEGV(“分段错误”)。你没有任何机会在DOS下使用Turbo / Borland C - 这是我可以想象这不会崩溃的唯一场景。 Windows不会说SIGSEGV,但它仍然不允许你的代码工作。
当然,您可能会因为您位于文件的末尾而被保存,因此根本不会阅读任何内容。
也许你的意思是:
char buf[200];
while (read(f,buf,200) > 0) ....