简体   繁体   English

fwrite有问题,fgets处理它

[英]Having issues with fwrite and fgets processing it

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

The context of this code is not hugely important. 此代码的上下文不是很重要。 The problem is that let's say fgets takes in "ls", "date", and "history". 问题在于,假设fgets接受“ ls”,“ date”和“ history”。 The resulting output is: 结果输出为:

1  ls
2   3  te
4   5  ory
6 

It should be: 它应该是:

1  ls
2  date
3  history

Since feature requests to mark a comment as an answer remain declined, I copy the above solution here. 由于功能请求将评论标记为答案的请求仍然被拒绝,因此我将上述解决方案复制到此处。

Looks like you get some '\\r's in your buffer. 看起来您的缓冲区中有一些'\\ r'。 And you should probably only fwrite strlen(string) bytes. 而且您可能应该只fwrite strlen(string)个字节。 – Daniel Fischer –丹尼尔·菲舍尔(Daniel Fischer)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM