Search code examples
cvariablestext-filesfilepathfopen

File name variable in file path in C


So I am writing a program that uses text files. I have a line of code that goes like this.

pfw = fopen(fileName, "w");

I am trying to make that program to create a txt file in this relative path

./TextFiles/

I have no idea how to implement a fileName variable in the file path. I usually do it like this when I have static fileName and program doesn't ask me to give it a file name or where fileName is not a variable and it works.

pfw = fopen("./TextFiles/fileName.txt", "w");

Solution

    • #define the relative path if configuration files are not being used
    #define BASE_DIR "./TextFiles/"
    
    char* finalName = malloc (strlen(BASE_DIR) + strlen(fileName) + 1);
    if (!finalName) { /* error handling */ }
    
    sprintf (finalName, "%s%s", BASE_DIR, fileName);
    
    FILE* pfw = fopen(finalName, "w");
    /*
    ...
    */
    // free after usage
    free (finalName);