【发布时间】:2020-05-17 19:34:53
【问题描述】:
我的意思是将文件描述符与文件指针相关联并使用它来写入。
我在下面整理了程序io.cc:
int main() {
ssize_t nbytes;
const int fd = 3;
char c[100] = "Testing\n";
nbytes = write(fd, (void *) c, strlen(c)); // Line #1
FILE * fp = fdopen(fd, "a");
fprintf(fp, "Writing to file descriptor %d\n", fd);
cout << "Testing alternate writing to stdout and to another fd" << endl;
fprintf(fp, "Writing again to file descriptor %d\n", fd);
close(fd); // Line #2
return 0;
}
我可以交替注释第 1 行和/或第 2 行,编译/运行
./io 3> io_redirect.txt
并检查io_redirect.txt 的内容。
只要第 1 行没有注释,它就会在io_redirect.txt 中生成预期的行Testing\n。
如果第 2 行被注释,我会得到预期的行
Writing to file descriptor 3
Writing again to file descriptor 3
在io_redirect.txt。
但是如果没有注释,这些行就不会出现在io_redirect.txt中。
- 这是为什么呢?
-
fdopen的正确使用方法是什么?
注意。
这似乎是对Smart-write to arbitrary file descriptor from C/C++ 的(部分)回答的正确方法
我说“部分”是因为我可以使用 C 风格的fprintf。
我仍然想使用 C++ 风格的stream<<。
编辑:
我忘记了fclose(fp)。
这“关闭”了问题的一部分。
【问题讨论】:
-
如果您发现了您的问题之一,您可以删除它而不是添加更正吗?
-
@tadman - 我检查过,
fclose(fp):或fflush(fp): close(fd):工作正常。它们是等价的吗? -
您混合了缓冲和无缓冲的写入,这总是一个问题。这里的用例是什么?您应该选择一种且只有一种方法与实际代码中的文件句柄进行交互。只要你保持一致,任何方法都可以。如果您需要从一种方法切换到另一种方法,请确保在切换后刷新并避免写入。
-
@tadman - 太好了。相关:stackoverflow.com/a/61708362/2707864
-
@JohnKugelman - 因为我认为我理解了问题的答案。但我觉得我没有一个权威的答案,cmets 发帖说明了这一点。我觉得,在这种情况下,它更有用。在其他情况下,我当然会编辑以删除问题。