开发者

C Programming fprintf issue

I have a problem when writing a file on the text. As you could see, I used \n to put another set of my data on the next line. The problem is when i close the file and save again the data per line which ends with \n becomes \n\n and so on. That's 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 are garbage value in between... 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);  
     }                   
}

Help please... any suggestions will be appreciated. Thank you in advance.


Not sure of what you exactly do but if you parse back the file before saving it again probably you are forgetting to remove the old \n from the original last string..

EDIT: this is actually right. The OP uses fgetsfunction, which includes the line terminator.

So starting from "test, test, test\n" with strtok he will obtain "test" "test" "test\n" so that when it will be saved back a new newline (forget it) is added to the file.

You could fix it by setting last character to null with

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

(it is safe since fgets return a null-terminated string by itself)

You can also add \n to delimiters used, you should end up with same behavior (not sure about empty tokens with strtok but IIRC they are just discarded).


I'm guessing this is on windows -- change your line:

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

to:

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

And you won't get extra \rs.

Alternatively, maybe the last of the strings you're fprintfing already has a newline at the end.


I'd guess that your array[i]->course field contains the \n previously written in the last save. Check the code that populates the array and make sure it is skipping newline characters.


Here:

fgets(linebuffer, 45, stream);

remove the trailing \n from linebuffer if there is one:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜