【发布时间】:2012-01-19 13:47:29
【问题描述】:
我有一个 C++ 类 Archive 和一个成员函数 extractData()。此函数调用realExtractData(),它在单独的 C 库中实现。
我想向extractData() 函数传递一对FILE * 实例,通常是stdout 和stderr,但我也想提供自定义文件指针的选项:
class Archive {
public:
...
int extractData(string id, FILE *customOut, FILE *customErr);
...
};
int
Archive::extractData(string id, FILE *customOut, FILE *customErr)
{
if (realExtractData(id.c_str(), customOut) != EXIT_SUCCESS) {
fprintf(stderr, "something went wrong...\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
如果我按所列方式调用上述内容,则将数据输出到标准输出没有延迟。所有提取的数据几乎立即发送到标准输出 (stdout):
FILE *outFp = stdout;
FILE *errFp = stderr;
Archive *archive = new Archive(inFilename);
if (archive->extractData(id, outFp, errFp) != EXIT_SUCCESS) {
fprintf(errFp, "[error] - could not extract %s\n", archive->getInFnCStr());
return EXIT_FAILURE;
}
如果我更改extractData() 使其fprintf() 调用使用customErr:
int
Archive::extractData(string id, FILE *customOut, FILE *customErr)
{
if (realExtractData(id.c_str(), customOut) != EXIT_SUCCESS) {
fprintf(customErr, "something went wrong...\n"); /* <-- changed this line */
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
...然后当我运行二进制文件时,二进制文件似乎在处理输入和打印到标准输出时挂起。
如果我将fprintf() 改回使用stderr 而不是customErr,那么一切都会再次正常运行,即,数据会立即刷新到标准输出(我的customOut)。
这是一个缓冲问题吗?有没有办法解决这个问题?
【问题讨论】:
标签: c++ c stdout stderr buffering