我有一個讀取文件并處理它的 C++ 任務(wù):// A.m.cpp std::string filename = "myfile.txt"; std::ifstream file(filename.c_str()); std::ifstream file1(filename.c_str()); std::string line1; while(getline(file1, line1)){ // process some logic } for(;;){ file.getline(buffer); if (file.eof()) break; // process some other logic }我有一個 python 腳本來設(shè)置測試數(shù)據(jù)并運行任務(wù):import unittest def test_A(): file='myfile.txt' with open(file, 'w') as filetowrite: filetowrite('testdata') subprocess.run(["A.tsk"])但是,當(dāng)我運行 python 腳本并執(zhí)行 c++ 任務(wù)時,第一個 while 循環(huán)有效,但 for 循環(huán)只是在此處中斷 eof 的 bc :for(;;){ file.getline(buffer); // buffer is "testdata" if (file.eof()) break; // it breaks even buffer is "testdata" // process some other logic }我打印了buffer它,它有“testdata”,但是它只是在下一行中斷,所以它沒有得到處理,這不是我想要的。但是,如果我不使用 pythonsubprocess運行它,也不使用 Python 設(shè)置測試數(shù)據(jù),而只是手動echo testdata >> myfile.txt編譯A.m.cpp和運行A.tsk,則它不會中斷 for 循環(huán)并成功處理“testdata”。出什么問題了subprocess?為什么有內(nèi)容eof也會觸發(fā)?buffer
1 回答

牧羊人nacy
TA貢獻1862條經(jīng)驗 獲得超7個贊
您應(yīng)該在處理后放置 .eof() 中斷:
for(;;){ file.getline(buffer); // buffer is "testdata" // process some other logic if (file.eof()) break; }
即使在讀取數(shù)據(jù)后遇到 EOF,您也需要處理數(shù)據(jù)。請注意,這可能會在緩沖區(qū)中提供空字符串,因此您可能需要在處理代碼中處理這種情況。
您還需要將 python 行更改為:
filetowrite.write("testdata\n")
添加回答
舉報
0/150
提交
取消