Safety check prior to using fdopen

↘锁芯ラ 提交于 2020-06-09 07:07:04

问题


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/61860823/safety-check-prior-to-using-fdopen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!