c - fwrite 和 fgets 处理它时遇到问题

标签 c

 char string[50], s[50];
 File *f = tmpfile();
 count = 1;

 while (fgets(string, 50, stdin)) {
    if (string[0] == '!') {
        rewind(f);
    } else {
        fwrite(string, 50, 1, f);
    }

    if (strcmp("history\n", string) == 0) {
        rewind(f);
        while(fgets(s, 50, f)) {
            printf("\t%d  %s", count, s);
            count++;
        }
        count = 1;
    }
 }

这段代码的上下文并不是很重要。问题是,假设 fgets 接受“ls”、“date”和“history”。结果输出是:

1  ls
2   3  te
4   5  ory
6 

应该是:

1  ls
2  date
3  history

最佳答案

自从功能请求 mark a comment as an answer仍被拒绝,我将上述解决方案复制到此处。

看起来您的缓冲区中有一些 '\r'。你可能应该只写 fwrite strlen(string) 字节。 – 丹尼尔·费舍尔

关于c - fwrite 和 fgets 处理它时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10889430/

相关文章:

c - 如何将函数放入宏中?

编译 PHP 扩展

c - 反转字符串数组

C sscanf ("%hhx") 读取 unsigned int 而不是 unsigned char

c - 如何通过C中的PID监视外部进程的事件?

c - 计算函数返回值的最佳实践

C 数组不保留值

c++ - 无法溢出 Shell 编码的缓冲区

c++ - 是否有预处理器定义来区分 gcc 和 g++ 代码?

C - 使用 fork()、pipe()、select()、execl() 和 write() 未达到正确的结尾