【问题标题】:Popen in c on Windows: Output not being returned?在 Windows 上以 c 语言打开:未返回输出?
【发布时间】:2014-09-25 17:44:51
【问题描述】:

所以我使用以下代码来尝试查找所有头文件,将它们的位置打印到 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);

【问题讨论】:

  • 你是在 Cygwin 下使用这个还是别的什么? Windows 版本应命名为_popen()(请参阅msdn.microsoft.com/en-us/library/96ayss4b.aspx)。
  • 什么是bufferkren,它在哪里声明?一旦我将bufferkren 更改为buffer,此代码对我有效(在wine 中)。

标签: c file pipe command-prompt popen


【解决方案1】:
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() */
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 2022-06-16
    • 2011-05-19
    • 1970-01-01
    相关资源
    最近更新 更多