I am trying to write to a file in C using fopen but the extension of the file I want to write to must be a variable.
The extension is stored in the variable extension, while the text I want to write is stored in result.
I tried to use this function but no file is created.
void createAndWrite(char* result, char* extension){
char buf[100];
sprintf(buf,"%s.%s","outputFile",extension);
FILE *fh = fopen (buf, "wb");
if (fh != NULL) {
fwrite (result, sizeof (result), 1, fh);
fclose (fh);
}
}
If I manually write the name of the file it works perfectly e.g. FILE *fh = fopen ("outputFile.txt", "wb");: the file is created and the output is correct.
I also tried using functions like strcat(), snprintf() or specifying the whole file path but nothing works.
It's not a problem of accessing to the the extension variable bacause if I do a printf("%s",buf); I can see the correct file.
How con I solve it?
fwrite()call doesn't look right.sizeof (result)?resultis anul-terminated character string, then you wantstrlen(result)in place ofsizeof (result). (Or, more likely,strlen(result)+1!)sizeof (result)will be the size of achar *which will probably be 4 or 8 on your system. You probably wantstrlen(result)or usefputsinstead offwrite.