我的意思是将文件描述符与文件指针相关联并将其用于写入。我把程序放在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
什么?
注意。这似乎是从 C/C++ 智能写入任意文件描述符的(部分)答案的正确方法
我说“部分”,因为我可以使用 C-style fprintf
。我仍然想使用 C++-style stream<<
。
编辑:我忘记了fclose(fp)
。这“关闭”了问题的一部分。