I've got some code that was working on a server until it was moved to a different system. The problem seems to be here:
given a structure I've defined elsewhere:
user1_type user1; /* structure containing user data */
user1_type *user1_ptr=&user1;
this routine appends the record to the end of the file
if ((dfile=fopen(filename,"ab+"))==NULL)
error_message("Unable to open file for append.",filename,1);
else { /* append data */
user1.recid=ftell(dfile); /* update file position */
fwrite(user1_ptr,sizeof(user1),1,dfile);
fflush(dfile);
fclose(dfile);
I can confirm the data gets appended in the file, but the value of user1.recid always returns 0 - any ideas why?
UPDATE: Looks like the issue is not all implementations require a fseek() after fopen(). I obviously need an fseek(dfile,0,SEEK_END); before I do a ftell() when appending. But if I want to read from the beginning of a text or binary file, is it also customary to place a fseek() right after fopen? Does it vary depending upon the file type?
From MSDN's documentation of ftell
The position returned by
ftell()is expressed as an offset relative to the beginning of the streamIf no I/O operation has yet occurred on a file opened for appending, the file position is the beginning of the file.
This gives you an offset of 0 relative to the beginning.
So when you call user1.recid=ftell(dfile); no I/O operation has occurred on the stream yet so ftell() returns 0 indicating the file pointer position is at the begining.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With