正确使用fdopen的方法

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() {
    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

and check the contents of io_redirect.txt. Whenever line 1 is not commented, it produces in io_redirect.txt the expected line Testing\n. If line 2 is commented, I get the expected lines

Writing to file descriptor 3
Writing again to file descriptor 3

in io_redirect.txt. But if it is not commented, those lines do not show up in io_redirect.txt.

  • Why is that?
  • What is the correct way of using fdopen?
  • Should I perform some kind of checking for availability of fd=3 prior to using it with either write(fd, ... or fdopen(fd, ...?

EDIT: I was forgetting about fclose(fp). That "closes" part of the question.