I am still pretty new to C and I learned a lot from this forum. This is a working code (In windows by the way). I already learned that you don't have to cast the return of malloc. I am wondering if you can give me tips on how can I improve my C coding techniques or if you spot a bad habbit (like casting malloc's return value).
This function will create a file making sure all sub-directory exists before creating the file.
Code:
int edb_create_file(char * path, FILE *fl) {
char *dirPath = strdup(path);
if(!dirPath)
return EDB_OUT_OF_MEMORY;
// This will remove the file name so it will only have the directory
*(strrchr(dirPath, '\\') + 1) = '\0';
// Check if parent dir exist if not make sure
// all sub-dir exist and created before adding the file
if(access(dirPath, F_OK) != 0)
{
char *curPath = malloc(strlen(dirPath)); // Current Path
if(!curPath)
return EDB_OUT_OF_MEMORY;
char *nxtPath = strstr(dirPath, "\\"); // Get the first occurance of '\\'
do {
++nxtPath; // Skip "\\" so strstr() will not see it next time.
// Copy dirPath until nxtPath
strncpy(curPath, dirPath, nxtPath - dirPath);
*(curPath + (nxtPath - dirPath)) = '\0';// Add '\0' to the end of curPath
if(access(curPath, F_OK) != 0) // Check if dir doesn't exist
if(mkdir(curPath) != 0) // Create dir
return EDB_CREATE_FAILED; // Exit when failed
nxtPath = strstr(nxtPath, "\\"); // Get the next dir
} while(nxtPath);
free(curPath);
}
free(dirPath);
fl = fopen(path,"wb");
if(fl)
return EDB_SUCCESS;
else
return EDB_CREATE_FAILED;
}