简体   繁体   English

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

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

I have a text file "123.txt" with this content: 我有一个文本文件“ 123.txt”,其内容如下:

123456789 123456789

I want the output to be: 我希望输出为:

123 123
456 456
789 789

This means, a newline character must be inserted after every 3 characters. 这意味着必须在每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);
}

My code works fine, but prints a newline character also at the end of file, which is not desired. 我的代码工作正常,但是在文件末尾也打印换行符,这是不希望的。 This means, a newline character is added after 789 in the above example. 这意味着,在上面的示例中,在789之后添加了换行符。 How can I prevent my program from adding a spurious newline character at the end of the output file? 如何防止程序在输出文件的末尾添加伪造的换行符?

As indicated in the comments, your while loop is not correct. 如注释中所示,您的while循环不正确。 Please try to exchange your while loop with the following code: 请尝试将您的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++;
}

Example: A file containing: 示例:包含以下内容的文件:

12345 12345
123456789 123456789

is turned into a file containing: 变成包含以下内容的文件:

123 123
45 45
123 123
456 456
789 789

I think you should do your new line at the beggining of the 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++;
}

I can't test it right now, maybe there is some mistakes but you see what I mean. 我现在无法测试,也许有一些错误,但是您明白我的意思了。

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

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