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:
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);