1

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?

7
  • Try at the beginning to fill buf with \0, maybe it has some garbage from memory. Commented Jan 6, 2021 at 17:22
  • 3
    That fwrite() call doesn't look right. sizeof (result)? Commented Jan 6, 2021 at 17:23
  • If result is a nul-terminated character string, then you want strlen(result) in place of sizeof (result). (Or, more likely, strlen(result)+1!) Commented Jan 6, 2021 at 17:23
  • Also needs a minimal reproducible example and better description of what "nothing happens" means. Commented Jan 6, 2021 at 17:23
  • 2
    sizeof (result) will be the size of a char * which will probably be 4 or 8 on your system. You probably want strlen(result) or use fputs instead of fwrite. Commented Jan 6, 2021 at 17:23

1 Answer 1

1
sizeof(char* result) will always result in 4 (32 bit target) or 8 (64 bit target)

Unless the actual length of result matches 3 or 7 bytes (considering also the NULL terminator) the wrong length information will cause fwrite (result, sizeof (result), 1, fh); to fail. Replace this with:

fwrite (result, strlen(result) + 1, 1, fh);

Aside: (not part of the primary problem) Regarding the following:

char buf[100];
sprintf(buf,"%s.%s","outputFile",extension);

Even though sprintf() does append a \0 termination to the resulting buffer for a successful call, as a rule it is a good habit to initialize. buffers to be used in string functions. Eg: :

 char buf[100] = {0};//populates entire memory location with `nul` characters.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.