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);

}
4

1 回答 1

0

您看到的空间可能是最后一行末尾的换行符。

如果您希望将换行符视为行之间的分隔符或终止符(因此最后一行也应该有换行符),这一切都归结为。IMO 换行符最常见的用途是作为终止符,甚至有文本编辑器会在找不到时添加这样的换行符。

例如,一个有效的 C 源文件应该以换行符结尾,即使这意味着在某些编辑器中它看起来就像结尾有一个空行。

如果您不喜欢换行符作为终止符,您可以稍微更改代码,以便在除第一行之外的每一行添加换行符,而不是在末尾附加换行符:

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);
}
于 2013-09-22T12:24:15.570 回答