-2

I want to input text from stdin and then display it on the screen, while numbering the lines. The last part of my program is not working, I don't know how to use the read() function correctly.

#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;
}
4

2 回答 2

2

First of all you consume stdin:

while (fgets(s,200,stdin) != NULL)
    write(f,s,strlen(s));

Then you attempt to read from the file f. However, the file f is already at its end, and so the first call to read() returns 0. Since there is nothing to read. You would need to move the file pointer back to the beginning of the file.

But your read() based loop will still not do what you want. That's because you want line oriented input. So you should use fgets rather than read. Just in the same way that you handled stdin in a line oriented way, you need to handle your printing to stdout.

And as Mats points out, you never allocated buf. So if there had been anything to read, you would be de-referencing an un-initialized pointer.

Having said all of that, it would seem to me to make more sense to run just a single loop. Call printf() inside the loop that calls write().

while (fgets(s,200,stdin) != NULL)
{
    write(f,s,strlen(s));
    printf("%d %s", i, s);
    i++;
}
于 2012-12-26T16:41:08.940 回答
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) ....
于 2012-12-26T17:14:56.137 回答