Search code examples
cfilepipecommand-promptpopen

Popen in c on Windows: Output not being returned?


So I use the following code in an attempt to look for all header files, print their locations to STDOUT and read them from there. All I get when I run this code is, well, nothing actually. The FILE is not NULL but has no contents. Ideas?

NOTE: This is in C on a Windows 7 Platform

char buffer[512];
//Output the list of directories whee headers are located to a file
FILE *IncludeDirs = fopen("IncludeDir.txt", "w+");
FILE * pipe = popen("for /r %i in (*.h) do echo %~pi" , "r");

if (pipe == NULL)
{
    //This line never hit
    fprintf(IncludeDirs, "We have a Problem...",IncludeDirs);
}
while(fgets(buffer, 500, pipe)!=NULL)
{
    //These lines are never executed either
    printf(buffer);
    fprintf(IncludeDirs, "-I %s",buffer);
}
fclose(IncludeDirs);

Solution

  • There seems to be several problems with the presented code. The following is the recommended method for reading file names using popen(). effectively, in the following code, the popen function returns a pointer to a virtual file that contains a list of '\n' separated strings that can be individually read using the fgets function:

    #include <stdio.h>
    ...
    
    
    FILE *fp;
    int status;
    char path[PATH_MAX];
    
    
    fp = popen("ls *.h", "r");
    if (fp == NULL)
        /* Handle error */;
    
    
    while (fgets(path, PATH_MAX, fp) != NULL)
        printf("%s", path);
    
    
    status = pclose(fp);
    if (status == -1) {
        /* Error reported by pclose() */
        ...
    } else {
        /* Use macros described under wait() to inspect `status' in order
           to determine success/failure of command executed by popen() */
        ...
    }