因此,我使用以下代码尝试查找所有头文件,将它们的位置打印到 STDOUT 并从那里读取它们。当我运行这段代码时,我得到的实际上是什么也没有。 FILE 不为 NULL,但没有内容。有想法吗?
注意:这是 Windows 7 平台上的 C 语言
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);
所提供的代码似乎存在几个问题。 以下是使用 popen() 读取文件名的推荐方法。 有效地,在下面的代码中, popen 函数返回一个指向虚拟文件的指针,其中包含 的列表 ' ' 分隔的字符串 可以使用 fgets 函数单独读取:
#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() */
...
}