How do I read the results of a system() call in C++?

后端 未结 9 902
醉梦人生
醉梦人生 2020-12-17 06:44

I\'m using the following code to try to read the results of a df command in Linux using popen.

#include  // file an         


        
相关标签:
9条回答
  • 2020-12-17 07:36

    I'm not sure you can fseek/ftell pipe streams like this.

    Have you checked the value of bufSize ? One reason malloc be failing is for insanely sized buffers.

    0 讨论(0)
  • 2020-12-17 07:36

    To answer the question in the update:

    char buffer[1024];
    char * line = NULL;
    while ((line = fgets(buffer, sizeof buffer, fp)) != NULL) {
        // parse one line of df's output here.
    }
    

    Would this be enough?

    0 讨论(0)
  • 2020-12-17 07:40

    First thing to check is the value of bufSize - if that happens to be <= 0, chances are that malloc returns a NULL as you're trying to allocate a buffer of size 0 at that point.

    Another workaround would be to ask malloc to provide you with a buffer of the size (bufSize + n) with n >= 1, which should work around this particular problem.

    That aside, the code you posted is pure C, not C++, so including is overdoing it a little.

    0 讨论(0)
提交回复
热议问题