How to catch file mode?

。_饼干妹妹 提交于 2021-01-27 12:24:17

问题


I have to catch modes below:

"rb", "r+b" and "wb".

I tried to execute code (compiled) of this:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    FILE *file = fopen("data.bin", "r");
    if (!file){
        perror("");
        return -1;
    }

    int fd = fileno(file);
    if (fcntl(fd, F_GETFL) == O_RDONLY){
        printf("read only\n");
    }

    // printf("%d\n", O_APPEND);

    fclose(file);
    return 0;
}

But gotten nothing printed. fcntl() returns integers like 32768, but I need macros from the library like O_RDONLY.


回答1:


In general, you cannot catch -given a FILE* handle-, the file mode, in the fopen sense, with a portable C program.

For example, your FILE* might be obtained with popen, fmemopen, open_memstream, fdopen, etc... and could be writable only or readable only. It might not even have a valid file descriptor given by fileno.

You should adopt and define and document conventions about them.

For example, on Linux, a socket might be readable and writable at the OS level, and you could have two different FILE* handles on it (using fdopen) for the read and for the write sides.

And of course, a FILE* handle is not usable after an fclose (or a pclose)

So an hypothetical routine fprint_stuff(FILE*, struct stuff_st*) should document that the first argument is a writable file handle, and would just call fwrite and fprintf but should check that these did not fail.



来源:https://stackoverflow.com/questions/54421107/how-to-catch-file-mode

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