cfilesyntaxfopenmkdir

Can't use fopen and mkdir in same program


I'm working on creating files with valid syntax possibilities that can be compiled later. I started by using the fopen method to create files, and then I added the mkdir() function to handle file creation. However, I've run into a peculiar issue where I can't use both functions together in the same program. The compiler seems to prefer executing only the fopen function. It's worth noting that both functions work fine individually. Can you help me understand why this is happening?

#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>

int main(){
    FILE *fprt;
    char *filename = "File";

    fprt = fopen(filename,"w");

    if (!fprt ) // equivalent to saying if ( in_file == NULL )
             { 
                printf("oops, file can't be read\n");
             }


    mkdir(filename,0777);
    printf("\n");
}

Solution

  • You can use fopen and mkdir in the same program.

    You can't create a folder and a file with the same name at the same location.

    You encountered the latter as a problem and misunderstood it, thinking the former. mkdir creates a folder, it stands for

    make directory

    and you will not be able to create a file with it. So, what you likely wanted is to create a directory and then create a file into it. But then you will need to create the directory first and THEN the file and, make sure that the path of the file you create contains the directory you want it to be created into.