C Programming fprintf

I had a problem writing a file in text. As you can see, I used \nto put another set of my data on the next line. The problem is when I close the file and save the data in a line again, ending in \n, becomes \n\nand so on. This is why my file looks like this:

FIRST SAVE

 test, test, test
 test, test, test

SECOND SAVE

 test, test, test

 test, test, test

THIRD SAVE

test, test, test


test, test, test

that’s why when I display it on the screen ... there is a garbage value between me ... My code is as follows:

save(){
     int i = 0;
     FILE *stream = NULL;
     stream = fopen("student.txt", "wt");
     printf("\nSaving the student list directory. Wait a moment please...");
     printf("\nExiting the program...");
     for (i=0; i<recordCtr; i++){
        fprintf(stream, "%s, %s, %s\n", array[i]->studentID, array[i]->name, array[i]->course);  
     }                   
}

Please help ... any suggestions will be appreciated. Thank you in advance.

+3
source share
4 answers

, , , , \n .

EDIT: . OP fgets, .

, "test, test, test\n" strtok, "" "test" "test\n", , , ​​ ( ) .

, null

linebuffer[strlen(linebuffer)-2] = '\0'

( , fgets )

\n , ( strtok, IIRC ).

+5

, - :

stream = fopen("student.txt", "wt");

stream = fopen("student.txt", "wb");

\r s.

, , , fprintf ing .

+3

I assume that your field array[i]->coursecontains \ n previously written in the last save. Check the code that populates the array and make sure it skips the newlines.

+3
source

Here:

fgets(linebuffer, 45, stream);

remove the final \nfrom linebuffer, if any:

for (int i=strlen(linebuff)-1; i>=0 && linebuff[i]=='\n'; linebuff[i--]='\0');
+3
source

Source: https://habr.com/ru/post/1778232/


All Articles