Python 运行c++;任务读取文件错误 我有一个C++任务,它读取一个文件并处理它: // 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脚本来设置测试数据并运行任务:Python 运行c++;任务读取文件错误 我有一个C++任务,它读取一个文件并处理它: // 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,c++,unit-testing,subprocess,Python,C++,Unit Testing,Subprocess,我有一个python脚本来设置测试数据并运行任务: import unittest def test_A(): file='myfile.txt' with open(file, 'w') as filetowrite: filetowrite('testdata') subprocess.run(["A.tsk"]) 但是,当我运行Python脚本并执行C++任务时,第一个while循环工作,但是fo
import unittest
def test_A():
file='myfile.txt'
with open(file, 'w') as filetowrite:
filetowrite('testdata')
subprocess.run(["A.tsk"])
但是,当我运行Python脚本并执行C++任务时,第一个while循环工作,但是for循环正好打破了这里的EOF的B:
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来设置测试数据,而只是echo testdata>>myfile.txt
,然后编译A.m.cpp
并手动运行A.tsk
,那么它就不会中断for循环并成功地处理“testdata”。子流程
有什么问题?为什么它会触发eof
甚至buffer
也有内容?在处理之后,应该将.eof()中断:
for(;;){
file.getline(buffer); // buffer is "testdata"
// process some other logic
if (file.eof()) break;
}
即使在读取数据后点击EOF,您也会希望处理该数据。请注意,这会在缓冲区中为您提供空字符串,因此您可能希望在处理代码中处理这种情况
您还需要将python行更改为:
filetowrite.write("testdata\n")
testdata
后面没有换行符,因此在getline
之后设置eof
不是意外的吗?(虽然filetowrite('testdata')
似乎不是有效的python)哦,你是对的,那么我认为问题在于为什么echo testdata>>myfile.txt
可以工作,而filetowrite('testdata')
不能工作。。我猜echo
会在结尾追加\n
吗filetowrite('testdata')
甚至会运行吗?是的,我想这是因为echo testdata>>myfile.txt
和filetowrite('testdata')
之间的差异。但我认为我不应该改变C++代码,因为这是生产,我只需要改变我的测试。所以我猜echo test>>myfile.txt
会在末尾追加\n
,所以我应该使用filetowrite('testdata\n')
?@coder是,但是使用filetowrite.write(“testdata\n”)
。您试图在代码中调用那里的文件对象。