0

I have this function which saves in a text file the friends of each student. The names of students were saved in a different text files and the code for that is working fine, so i did not include it. However, when I view my friends.txt, I noticed that there's an extra "white space" below the supposedly end of the file. How do I remove this?

void save(student *h, student *t){
FILE *fp1;
student *y = h->next;
fp1 = fopen("friends.txt", "w");
    while(y != t){
        friend *y1 = y->friendh->next;
        if(y1 != y->friendt){
                while(y1 != y->friendt->prev){ 
                    fprintf(fp1, "%s ", y1->friends);
                    y1 = y1->next;
                }
                if(y1 == y->friendt->prev){
                    fprintf(fp1, "%s\n", y1->friends);
                }
        }
        y = y->next;
    }
fclose(fp1);

}

1 Answers1

0

The space you're seeing is probably the newline at the end of the last line.

It all boils down if you want the newline to be considered a separator between lines or a terminator (so last line should have a newline too). IMO most common use of newline is as terminator and there are even text editors that will add such a newline when it's not found.

For example a valid C source file should terminate with a newline character, even if this means that in some editors it will appear like there's an empty line at the end.

If you don't like the newline to be a terminator you could change the code slightly so that instead of appending a newline at the end you prepend a newline on each line except the first:

void save(student *h, student *t){
    int first = 1;
    FILE *fp1;
    student *y = h->next;
    fp1 = fopen("friends.txt", "w");
    while(y != t){
        friend *y1 = y->friendh->next;
        if (!first) fputc('\n', fp1);   /* Start on a new line */
        if(y1 != y->friendt){
                while(y1 != y->friendt->prev){ 
                    fprintf(fp1, "%s ", y1->friends);
                    y1 = y1->next;
                }
                if(y1 == y->friendt->prev){
                    fprintf(fp1, "%s", y1->friends);
                }
        }
        y = y->next;
        first = 0;
    }
    fclose(fp1);
}
Community
  • 1
  • 1
6502
  • 112,025
  • 15
  • 165
  • 265