【问题标题】:How to overwrite a struct inside a file using C?如何使用C覆盖文件内的结构?
【发布时间】:2012-06-13 23:32:09
【问题描述】:

我正在将结构保存到 .dat 文件中。假设我必须编辑一个特定的结构,我将如何进行?我做了以下事情:

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

所以,如您所见,我想用 newStruct 更新我的文件。

fwrite 函数返回 1,但它不会替换我想要的行(也不会替换相邻的行,以防我使用了丢失的索引),并且它不会向文件添加新结构。它根本什么都不做!

有什么想法吗?

我通过读取所有结构、用我的 newStruct 替换 index-struct 并用所有结构写入文件来做到这一点,但我正在寻找一种更好的方法来做到这一点。

提前致谢。

【问题讨论】:

  • 使用 W+ 不会删除整个文件吗?

标签: c file function edit fwrite


【解决方案1】:

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+ 模式,矛盾的是这也意味着

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

【讨论】:

  • @Renato "w" 打开用于写入,而 "r" 打开用于读取,但 "w" 也会截断文件(在写入前将其大小设置为 0)。后者的区别是“w+”和“r+”之间的主要区别,两者都以读/写方式打开文件。
  • 我每次使用fopen() 时都必须查找字符串。我讨厌界面。 :)
猜你喜欢
  • 2012-12-30
  • 1970-01-01
  • 2017-09-22
  • 2017-08-02
  • 2010-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多