[英]C++ Trouble reading and writing to text file using the fstream object
[英]Is there any bug inducing feature when reading and writing using the same fstream object in c++
我正在嘗試學習 C++ fstream、ifstream、ofstream。 在我的項目進行到一半時,我了解到如果我們使用 ofstream 和 ifstream 訪問同一個文件進行讀寫,最好關閉流,然后再使用另一個流。
像 ofstream write_stream(...); ifstream read_stream(....);
// Accessing pointers using both read_stream, write_stream interchangebly
read_stream.read(....);
write_stream.write(....);
read_stream.close();
write_stream.close();
///
在上面的例子中,我猜 stream 在文件中使用了相同的指針,所以我需要知道指針的移動,所以我每次嘗試 read() 或 write() 時都必須查找。
我想,我是對的,到目前為止。
為了避免更多的混亂,我決定使用這種格式
fstream read_write_stream("File.bin",ios::in|ios::out|ios::binary);
read_write_stream.seekp(pos);
read_write_stream.seekg(pos);
read_write_stream.tellp();
read_write_stream.tellg()
read_write_stream.read(...);
read_write_stream.write(...);
read_write_stream.close()
在上面的程序中是否有任何我應該注意的錯誤誘導功能??? 請指教
雖然我不知道標准是否明確提到這種情況,但我不認為 C++ 編譯器可以 promise 如果您使用多個流更改相同的外部資源(在本例中為文件),會發生什么情況. 除了 fstream 內部實現之外,它還取決於操作系統和您寫入的硬件。 如果我是正確的,默認情況下,它會使此操作成為未定義的行為。
如果您使用兩個不同的流,很可能每個流都會管理自己的 put 和 get 指針,每個流都有緩沖,這意味着如果您不使用 flush(),您將無法確定操作的順序將在文件上完成。
如果您使用一個 stream 進行讀取和寫入,我認為該行為將是可預測的並且更容易理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.