python子进程运行c++任务读取文件错误

python subprocess running c++ task reading file error

我有一个读取文件并处理它的 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 脚本来设置测试数据和 运行 任务:

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 的 bc:

for(;;){
       file.getline(buffer); // buffer is "testdata"
       if (file.eof()) break;  // it breaks even buffer is "testdata"
      // process some other logic
    }

我打印了 buffer 并且它有“testdata”,但是它只是在下一行中断所以它没有得到处理,这不是我想要的。但是,如果我不使用 python subprocess 到 运行 它也不使用 Python 设置测试数据,而只是 echo testdata >> myfile.txt,然后编译 A.m.cpp 和 运行 A.tsk 手动,它没有中断 for 循环并成功处理“testdata”。 subprocess 有什么问题?为什么 eof 即使 buffer 有内容也会触发?

您应该在处理后放置 .eof() 中断:

for(;;){
    file.getline(buffer); // buffer is "testdata"
    // process some other logic
    if (file.eof()) break;
}

即使在读取数据后遇到 EOF,您也需要处理数据。请注意,这可能会在缓冲区中为您提供空字符串,因此您可能希望在处理代码中处理这种情况。

您还需要将 python 行更改为:

filetowrite.write("testdata\n")