0

I have a directory that when i run a ls command on, I know that it spits out an error like so:

ls: reading directory /mydir: Input/output error

I want to be able to detect that there was an IO error in my code.

This is what i've tried:

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

The error message prints out to the screen but i don't get the error message when reading from the pipe.

Thanks,

georges
  • 175
  • 4
  • 17

1 Answers1

0

Conversely, reading from the stream reads the command's standard output

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

You are reading the standard input of the invoked program, which is empty. The error message is written to the standard output. Try executing ls 2>&1.

erenon
  • 18,838
  • 2
  • 61
  • 93