简体   繁体   English

如何使用C覆盖文件中的结构?

[英]How to overwrite a struct inside a file using C?

I'm saving a struct into a .dat file. 我正在将结构保存到.dat文件中。 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. 所以,如你所见,我想用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. fwrite函数返回1,但它不会替换我想要的行(也不会替换邻居行,以防我使用错过的索引),并且它不会向文件添加新结构。 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. 我通过读取所有结构,使用newStruct替换index-struct并使用所有结构编写文件来完成它,但我正在寻找更好的方法来实现它。

Thanks in advance. 提前致谢。

fopen(.., "ab+") is asking for append mode : 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.

You probably need r+ mode, which paradoxically also means write : 你可能需要r+模式,矛盾的是也意味着

   r+     Open for reading and writing.  The stream is
          positioned at the beginning of the file.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM