【问题标题】:cpp popen get ls error [duplicate]cpp popen得到ls错误[重复]
【发布时间】:2016-05-18 17:57:18
【问题描述】:

我有一个目录,当我在其上运行 ls 命令时,我知道它会吐出如下错误:

ls: reading directory /mydir: Input/output error

我希望能够检测到我的代码中存在 IO 错误。

这是我尝试过的:

void readLs(const std::string& name)
{
    stringstream ss;
    ss << "ls " << name;
    FILE* apipe = popen(ss.str().c_str(), "r");
    if(apipe == NULL)
    {
            cout << "Error opening popen" << endl;
            return;
    }
    char line[256];
    cout << __FILE__ << " " << __LINE__ << endl; //This is line 46
    while (  fgets( line, 256 , apipe) )
    {
            string temp(line);
            cout << "This is line: " << temp << endl;
            memset(line, 0, 256);
    }
    cout << __FILE__ << " " << __LINE__ << endl; //This is line 53
    pclose(apipe);
}


test.cpp 46
ls: reading directory /mydir: Input/output error
test.cpp 53

错误消息打印到屏幕上,但从管道读取时我没有收到错误消息。

谢谢,

【问题讨论】:

  • 完美!非常感谢,@antlersoft

标签: c++ popen ls


【解决方案1】:

相反,从流中读取命令的 标准输出

http://man7.org/linux/man-pages/man3/popen.3.html

您正在读取被调用程序的标准输入,它是空的。错误消息被写入标准输出。尝试执行ls 2&gt;&amp;1

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 2013-10-11
    • 2019-12-17
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    相关资源
    最近更新 更多