Search code examples
cfileansi-cbyref

How to know in which file it is a referenced fp is currently writing in?


The idea is, main opens few files, and writes to them given a condition, fp is passed by ref here and there, and writeresult is responsible to save in the actual file. Can we know in which file it is writing ?

#include <stdio.h>
#include <string.h>

void Write2File(char *iMessage, FILE *fp)
{
    fprintf(fp, "%s\n", iMessage);

    // can i know in here where it is printing ?
}

int main(int argc, const char * argv[])
{
    FILE *fp1, *fp2, *fp3, *fp4;
    char message[250];

    memset(message, '\0', 250);

    strncpy(message, "sample text", 10);

    fp1 = fopen("./output1.txt", "w+");
    fp2 = fopen("./output2.txt", "w+");
    fp3 = fopen("./output3.txt", "w+");
    fp4 = fopen("./output4.txt", "w+");

    Write2File(message, fp1);
    Write2File(message, fp2);
    Write2File(message, fp3);
    Write2File(message, fp4);

    fclose(fp1);
    fclose(fp2);
    fclose(fp3);
    fclose(fp4);

    return 0;
}

Solution

  • This is OS specific and there is no standard way. If you want to do it consistently you can define some data structure that will hold pathname along FILE handle and pass that around instead of plain FILE:

    struct file_handle {
      FILE *fs;
      char *path;
    };
    

    Usually, there is no direct correspondence between a file stream and a disk file. For example on Linux, a file stream can be associated with something that is not a disk file (device, socket, pipe) or a disk file which is accessible through many different names in the file system or has been deleted and is no longer accessible. On the other hand you can use /proc file system to check which files correspond to different file descriptors. This is how vim instance editing /etc/hosts looks like through /proc lenses:

    # ls -l /proc/8932/fd
    total 0
    lrwx------. 1 root root 64 Feb 24 18:36 0 -> /dev/pts/0
    lrwx------. 1 root root 64 Feb 24 18:36 1 -> /dev/pts/0
    lrwx------. 1 root root 64 Feb 24 18:36 2 -> /dev/pts/0
    lrwx------. 1 root root 64 Feb 24 18:36 4 -> /etc/.hosts.swp