我正在寫一個二進制文件在C++中,我遍歷到一個特定的位置,用新的內容寫下內容。我知道整數大小的內容,所以我跟蹤了位置並重寫了它。好像,流寫入函數插入或追加變量。有沒有一種方法,在那裏我可以在寫,而不是附加或在文件中插入我想寫一些二進制文件,我需要覆蓋文件內容,如何寫而不是插入
long word = sizeof(int) + sizeof(long) + sizeof(long);
std::ofstream file_write(filename, std::ios::out|std::ios::binary);
file_write.seekp(word);
long pos = file_write.tellp();
file_write.write((char *)&some_integer,sizeof(int));
file_write.close()
//some other location
file_write.seekp(pos);
file_write.write((char *)&some_other_integer,sizeof(int));
//這裏some_integer應該結束了寫some_other_integer。有沒有辦法做到這一點?
這將是像
值1,值2,值3
我也許能值5
然後更換價值2它應該看起來像
值1,值5, value3
如果您只是想覆蓋文件中的單個值,那麼您顯示的代碼將起作用。你確定你展示的代碼實際上代表了你正在使用的代碼嗎?你確定代碼不工作嗎? – 2012-04-10 05:00:07
對不起,我想它是這樣工作的,你是對的,我感到困惑,有一個不同的問題。很抱歉,發貼者,有沒有辦法刪除帖子? – howtechstuffworks 2012-04-10 05:23:12
嘿埃裏克,它不那樣工作。我刪除之前的信息,並在它之後推送信息。請參閱此鏈接瞭解更多代碼。 http://stackoverflow.com/questions/10096196/cant-over-write-on-a-specific-location-on-a-file-over-write-on-a-specific-loca – howtechstuffworks 2012-04-10 21:47:48