寫入程式每 2 秒寫入一個數字;讀取程式每 5 秒讀取最後一個數字。需同步存取同一檔案。
#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;
int main() {
ofstream ofs("D:/w.txt");
int num = 0;
while (true) {
ofs << ++num << endl;
cout << num << endl;
Sleep(2000);
}
ofs.close();
return 0;
}
讀取端需開啟檔案、定位至末尾、向前尋找最後一行、解析數字。建議使用檔案鎖(LockFileEx)或命名管道/共享記憶體替代檔案同步,效能與可靠度更高。
flush()。Boost.Interprocess、ZeroMQ、gRPC 等成熟 IPC 機制。