Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

Write to file in C using variable as file name

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?

question from:https://stackoverflow.com/questions/65600333/write-to-file-in-c-using-variable-as-file-name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...