2014-09-25 47 views
0

所以我使用下面的代碼試圖查找所有頭文件,將它們的位置打印到STDOUT並從那裏讀取它們。當我運行這個代碼時,我所得到的只是實際上沒有。 FILE不是NULL,但沒有內容。想法?在Windows上的c中的Popen:輸出不被返回?

注意:這是用C在Windows 7平臺

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); 
+0

你Cygwin的或別的東西下使用呢? Windows版本應命名爲_popen()(請參閱http://msdn.microsoft.com/en-us/library/96ayss4b.aspx)。 – uesp 2014-09-25 18:04:56

+0

什麼是'bufferkren',它在哪裏聲明?一旦我將'bufferkren'改爲'buffer',這段代碼就適用於我(在'wine'中)。 – 2014-09-25 20:22:04

回答

0
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() */ 
    ... 
}