View Full Version : append to a file
alaios
07-16-2005, 09:26 AM
Hi i use the following two lines to append to a file
if ((file=fopen(path,"a+"))==NULL){
return(1);
}
I have noticed as u can see from the file below (look to the timestamp)
that a+ appends to the beginning of the file
16/07/05 11:08:56 Monitor thread ends
16/07/05 11:08:55 Monitor thread starts
16/07/05 11:09:26 Monitor thread ends
16/07/05 11:09:24 Monitor thread starts
~
I want to append to the bottom of the file.. How i can do that?
Dr. Evil
07-16-2005, 05:14 PM
fseek()?
When opening a file in "a+" mode, writing ALWAYS occurs at the end of the file. Even if you use fseek() to change file position, the marker is moved to the end of the file before any write occurs.
There must be a problem elsewhere in your program... the "thread ends" is getting written before the "thread starts" string. Are you waiting till the end of the program to write both strings? Are you flushing the output buffer? Are you writing from different threads which may have syncronization issues? Are you writing from a recursive functions? Something is wrong...
alaios
07-17-2005, 07:28 AM
Look to the following code
long dropped;
logfile("Monitor thread starts",MONITORFLOGFILE);
do sth();
logfile("Monitor thread ends",MONITORLOGFILE);
The logfile is a function that opens the file and write the output to the file. ... As i have already said the file is opened with a+ flag.....What else should i check?
Not sure, you should trace the problem. You could try posting your logfile function.. or another piece of test code that exibits the same problem.
alaios
07-17-2005, 09:30 PM
I have solved the problems .. The logfile function opens the file and then uses fprintf ot put results in the file... I have added one mroe line that each times closes the file :)
I cant still understand why this line has fixed the problem
Right, if you look up to one of my previous posts I said Are you flushing the output buffer?
You always should flush the buffer after each write. fclose() flushes the buffer (writes to disk) before it closes the file, also if you don't want to close the file each time, you can use fflush() to do the job.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.