【问题标题】:How do I add a newline character after every 3 characters in C?如何在 C 中每 3 个字符后添加一个换行符?
【发布时间】:2015-07-26 14:11:27
【问题描述】:

我有一个包含以下内容的文本文件“123.txt”:

123456789

我希望输出是:

123
456
789

这意味着,必须在每 3 个字符之后插入一个换行符。

void convert1 (){
    FILE *fp, *fq;
    int i,c = 0;
    fp = fopen("~/123.txt","r");
    fq = fopen("~/file2.txt","w");
    if(fp == NULL)
        printf("Error in opening 123.txt");
    if(fq == NULL)
        printf("Error in opening file2.txt");
    while (!feof(fp)){
        for (i=0; i<3; i++){
            c = fgetc(fp);
            if(c == 10)
                i=3;
            fprintf(fq, "%c", c);
        }
        if(i==4)
            break;
        fprintf (fq, "\n");
    }
    fclose(fp);
    fclose(fq);
}

我的代码工作正常,但在文件末尾也打印了一个换行符,这是不希望的。这意味着,在上面的示例中,在 789 之后添加了一个换行符。如何防止我的程序在输出文件末尾添加虚假换行符?

【问题讨论】:

  • while (!feof(fp))always wrong
  • @melpomene 你能详细说明一下吗?
  • @Sebi:仔细阅读 feof 所做的事情,然后进一步阅读并思考其中的含义。如果这没有帮助,请阅读 melpomene 链接的问答。

标签: c file newline


【解决方案1】:

如 cmets 所示,您的 while 循环不正确。请尝试使用以下代码交换您的while 循环:

i = 0;
while(1)
{
    // Read a character and stop if reading fails.
    c = fgetc(fp);
    if(feof(fp))
        break;

    // When a line ends, then start over counting (similar as you did it).
    if(c == '\n')
        i = -1;

    // Just before a "fourth" character is written, write an additional newline character.
    // This solves your main problem of a newline character at the end of the file.
    if(i == 3)
    {
        fprintf(fq, "\n");
        i = 0;
    }

    // Write the character that was read and count it.
    fprintf(fq, "%c", c);
    i++;
}

示例:文件包含:

12345
123456789

变成一个文件,包含:

123
45
123
456
第789章

【讨论】:

    【解决方案2】:

    我认为你应该在 lopp 开始时做你的新行:

    // first read
    c = fgetc(fp);
    i=0;
    // fgetc returns EOF when end of file is read, I usually do like that
    while((c = fgetc(fp)) != EOF)
    {
       // Basically, that means "if i divided by 3 is not afloating number". So, 
       // it will be true every 3 loops, no need to reset i but the first loop has
       // to be ignored     
       if(i%3 == 0 && i != 0)
       {
         fprintf (fq, "\n");
       }
    
       // Write the character
       fprintf(fq, "%c", c);
    
       // and increase i
       i++;
    }
    

    我现在无法测试它,也许有一些错误,但你明白我的意思。

    【讨论】:

      猜你喜欢
      • 2019-11-16
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 2012-03-14
      相关资源
      最近更新 更多