问题
Motivated by Smart-write to arbitrary file descriptor from C/C++, I mean to associate a file descriptor with a file pointer and use that for writing.
I put together program io.cc
below:
int main() {
int nbytes;
const int fd = 3;
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);
fclose(fp);
return 0;
}
Should I perform some kind of checking for availability of fd=3
prior to using it with fdopen(fd, ...
?
I guess I could perform some operation the gives the next available file descriptor fdn
, and if fdn<=3
(and unless one did anything with stderr
/stdout
, it would be fdn=3
), then fd=3
is available.
Note that I want to specify the number for fd
, not get it as the return value from another function.
This possibly makes How to check if a given file descriptor stored in a variable is still valid? a different question, even if some or all of the answer may apply here.
Question Correct way of using fdopen dealt with a related issue.
来源:https://stackoverflow.com/questions/61866342/is-there-any-way-to-safely-and-successfully-write-to-a-hand-picked-file-descript