c - 如何使用 C 覆盖文件内的结构?

标签 c file function edit fwrite

我正在将结构保存到 .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 替换索引结构并使用所有结构写入文件来完成此操作,但我正在寻找更好的方法来做到这一点。

提前致谢。

最佳答案

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.

关于c - 如何使用 C 覆盖文件内的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11024822/

相关文章:

c - 通过信号 SIGQUIT 唤醒 sleep 守护进程

linux - linux使用符号链接(symbolic link)时如何使原文件不被删除

java - BufferedReader 与 Java 中的 RandomAccessFile

python - 在python中调用函数时跳出循环

c - 抓取 exec 的输出

c - 如何从客户端调用 C 服务器中的函数

c++ - tellg() 失败的可能原因?

c - 将指针传递给 C 中的函数

python - 如何使用函数本身返回的值重复函数?

c - 读取文件,修改每一行,将其存储到缓冲区中,一次打印