Question: When the problem is completed after the class, using the fopen () function to open a non-existent file with a "A +", the Write, read error occurs;
1 //after adding a user to enter a word, add a number to the word header to make sure the numbering follows the previous start sort2#include"stdio.h"3#include"stdlib.h"4 #defineMAX 405 6 intMainvoid){7FILE *FP;8 CharWords[max];9 intCount =1,Ten temp; One A if(fp = fopen ("Words.txt","A +")) ==NULL) { -fprintf (stderr,"open file \ "Words\" Failed! \ n"); -Exit1); the } - - //continue sorting starting from the last ordinal -Fseek (FP,0L, seek_set); + while(1){ - if(FP, fscanf"%d", &temp)! =1) + Break; A Else atcount++; - } -Puts"Enter a word to add to the file:"); - while(Gets (words)! = NULL && words[0] !=' /'){ -fprintf (FP,"%d:%s", count++, words); - } in -Puts"File Contents:"); to while(FP, fscanf"%s", words) = =1){ + puts (words); - } the * if(fclose (fp)! =0){ $fprintf (stderr,"failed to close the file! \ n");Panax Notoginseng } - the return 0; +}
Problem Code
The problem should be that the fopen () function opens a nonexistent file in a "A +" mode;
The following is quoted in the "C Language Chinese Network" (http://c.biancheng.net/cpp/html/250.html);
"A +" mode: Open a readable/writable file in an additional way. If the file does not exist, the file is created, and if the file exists, the written data is added to the end of the file, i.e. the original content of the file is retained (the old EOF character is not retained).
Normally the code should be no problem, because the "A +" way to open the file can read and write to the file, if the file does not exist to create!
After directly to the file to write the content, and then run the program to find that there will be no downtime, but because the original purpose of the program is to automatically create the file does not exist, then the problem my solution is to open the file for the first time in "a" mode, close the file flow pointer, and then re- The "R" was opened at the time, avoiding the occurrence of the situation.
Above, if you have any questions, I hope you can point it out.
The fopen () function opened a "A +" file and read and write problems occurred.