Search code examples
cgnufile-descriptor

Create GNU C File Descriptor Without File Handle


If I want to use a physical file along with other types of streams such as a socket, I can simply convert a file handle into a file descriptor:

#include <stdlib.h>
#include <stdio.h>

int main(void) {
        FILE *f = fopen("uniquefilename.ext", "w");
        int fd = fileno(f);
        printf("%d\n", fd);
        fclose(f);
        return 0;
}

Does the GNU Standard Library provide a way to obtain a physical file's descriptor directly? Something to the effect of:

int fd = some_call("file_name.ext", "mode");

It seems I need to note I am completely aware of how a descriptor is not implicitly bound to any specific file. I was misleading when I wrote "obtain a physical file's descriptor"; what I should have wrote is something like "create a descriptor enabling access to a specific physical file".


Solution

  • It does not.

    However, you can use the open function directly! This is part of Linux itself, not the C standard library (technically the C standard library provides a small wrapper to allow you to call it as a C function).

    Example usage:

    int fd = open("file_name.ext", O_RDWR); // not fopen
    // do stuff with fd
    close(fd); // not fclose
    

    Note: The man page recommends including <sys/types.h>, <sys/stat.h>, and <fcntl.h>, and for close you need <unistd.h>. That's quite a few headers, and I don't know if they're all necessary.