2012-06-13 25 views
1

我正在將結構保存到.dat文件中。讓我們假設我必須編輯一個特定的結構,我將如何繼續?我做了以下內容:如何使用C覆蓋文件中的結構?

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替換索引結構並用所有結構編寫文件來完成工作,但我正在尋找更好的方法來實現這一目標。

在此先感謝。

+0

也許使用的,而不是AB + W +? –

+0

使用W +我不會擦除整個文件? –

回答

2

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. 
+0

謝謝,工作得很好!我雖然那個r +只是爲了閱讀。 –

+0

@Renato「w」打開寫入,而「r」打開讀取,但「w」也截斷文件(在寫入之前將其大小設置爲0)。後者的區別是「w +」和「r +」之間的主要區別,兩者都打開文件讀/寫。 –

+0

我每次使用'fopen()'都必須查找字符串。我討厭界面。 :) – sarnold