简体   繁体   中英

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

I have a text file "123.txt" with this content:

123456789

I want the output to be:

123
456
789

This means, a newline character must be inserted after every 3 characters.

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. 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. Please try to exchange your while loop with the following code:

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
123456789

is turned into a file containing:

123
45
123
456
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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