如何在 C 中每 3 个字符后添加一个换行符?

How do I add a newline character after every 3 characters in C?

我有一个文本文件“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 循环不正确。请尝试用以下代码交换您的 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

我认为你应该在循环开始时换行:

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

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