I'm saving a struct into a .dat file. Lets suppose I have to edit one specific struct, how would I proceed? I did the following:
ptFile = fopen("funcionarios.dat", "ab+");
fseek(ptFile, index*sizeof(strFunc), SEEK_SET); //places the pointer at the struct I want
fwrite(&newStruct, sizeof(strFunc), 1, ptFile); //adds the new struct
So, as you see, I want to update my file with newStruct.
The fwrite functions returns 1, but it does not replace the line I want (nor the neighbor lines, in case I used the missed index), and it doesnt add a new struct to the file. It simply do nothing!
Any ideas?
I did it working by reading all the structs, replacing the index-struct with my newStruct and writing the file with all the structs, but I'm looking for a better way to do that.
Thanks in advance.
fopen(.., "ab+")
is asking for append mode:
a+ Open for reading and appending (writing at end of
file). The file is created if it does not exist. The
initial file position for reading is at the beginning
of the file, but output is always appended to the end
of the file.
You probably need r+
mode, which paradoxically also means write:
r+ Open for reading and writing. The stream is
positioned at the beginning of the file.