1

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.

4

1 に答える 1

4

fopen(.., "ab+")追加モードを要求しています:

   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.

おそらくモードが必要r+です。これは、逆説的にwriteも意味します。

   r+     Open for reading and writing.  The stream is
          positioned at the beginning of the file.
于 2012-06-13T23:44:52.387 に答える