相关疑难解决方法(0)

为什么"while(!feof(file))"总是错的?

我看到人们最近在很多帖子中试图读取这样的文件.

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char **argv)
{
    char *path = argc > 1 ? argv[1] : "input.txt";

    FILE *fp = fopen(path, "r");
    if( fp == NULL ) {
        perror(path);
        return EXIT_FAILURE;
    }

    while( !feof(fp) ) {  /* THIS IS WRONG */
        /* Read and process data from file… */
    }
    if( fclose(fp) == 0 ) {
        return EXIT_SUCCESS;
    } else {
        perror(path);
        return EXIT_FAILURE;
    }
}
Run Code Online (Sandbox Code Playgroud)

这个__CODE__循环有什么问题?

c file while-loop feof

550
推荐指数
4
解决办法
21万
查看次数

如何使用POSIX执行命令并在C++中获取命令输出?

我正在寻找一种方法来获取从C++程序中运行命令的输出.我已经看过使用system()函数,但这只会执行一个命令.这是我正在寻找的一个例子:

std::string result = system("./some_command");
Run Code Online (Sandbox Code Playgroud)

我需要运行一个任意命令并获取其输出.我看过Boost.org,但我找不到任何可以满足我需要的东西.

c++ posix system process return-value

427
推荐指数
8
解决办法
42万
查看次数

禁用分叉进程的stdout缓冲

我在C/C++中编写了一个代码,用于处理子进程,将stdin/stdout复制到管道末端并调用execvp.

一切正常(即父进程捕获stdin/err/out的输出)

问题是子缓冲区是缓冲的.

所以如果子代码看起来像这样:

printf("Enter any key and hit ENTER:\n");
fgets(line);
printf("read: %s\n", line);
exit(0);
Run Code Online (Sandbox Code Playgroud)

在父进程中,我没有看到"输入任何键:"行 - 只有在程序调用exit(自动刷新stdout缓冲区)或显式调用'flush(stdout)'后才会"刷新"它添加

我做了一些研究并尝试添加一个调用来禁用stdout缓冲,方法是添加一个调用:

setvbuf(stdout,NULL,_IONBF,0); 就在父进程中调用execvp(...)之前

所以相关代码现在看起来像这样:

int rc = fork();
if ( rc == 0 ) {
    // Child process
    if(workingDirectory.IsEmpty() == false) {
        wxSetWorkingDirectory( workingDirectory );
    }
    int stdin_file  = fileno( stdin  );
    int stdout_file = fileno( stdout );
    int stderr_file = fileno( stderr );

    // Replace stdin/out with our pipe ends
    dup2 ( stdin_pipe_read,  stdin_file );
    close( stdin_pipe_write );

    dup2 ( stdout_pipe_write, …
Run Code Online (Sandbox Code Playgroud)

c c++ posix

8
推荐指数
1
解决办法
4535
查看次数

标签 统计

c ×2

c++ ×2

posix ×2

feof ×1

file ×1

process ×1

return-value ×1

system ×1

while-loop ×1