Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Format error with sprintf to create file name buffer

I am using sprintf to format a file name buffer, but clang-10 reports:

warning: format specifies type ‘int’ but the argument has type ‘char
*’ [-Wformat] sprintf(file_name_buffer, "%c", file_name);

This is the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

char file_name[ ] = "/path/filename.bin";
int file_name_len = sizeof(file_name);
char file_name_buffer[file_name_len];
sprintf(file_name_buffer, "%c", file_name);
outfile = fopen(file_name_buffer, "wb+");

I thought %c is the format string for a char string. How do I format this for sprintf ?

Thanks

>Solution :

%c is for a single char and %s is for strings.

#include <stdio.h>

int main(void) {
    char file_name[] = "/path/filename.bin";
    int file_name_len = sizeof(file_name);
    char file_name_buffer[file_name_len];

    sprintf(file_name_buffer, "%s", file_name);
//                             ^^

    FILE *outfile = fopen(file_name_buffer, "wb+");
    if(outfile) {
        // success
    } else {
        // failure
    }
}

In this case, you may want to use strncpy instead of sprintf though since there’s not much of formatting going on in your sprintf.

#include <string.h>

//...

strncpy(file_name_buffer, file_name, sizeof file_name_buffer);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading