I've been trying to write a simple string to a file in C with fwrite()
.
When I define a simple string as:
char str[]="Hello World!";
and write it to a file as:
fwrite(str, sizeof(char), sizeof(str), fp);
Everything seems to work fine.
But as I make a custom string with sprintf_s
, the output file I get is:
畒湮湩湁祬敺浉条硥湯椠杭〰⸱灪㩧爠
Though printf
func will print the string correctly
The Complete Code:
#define MAX_ELEMENT_LENGTH 512
void GenerateResultLine(char *resultLineBuffer, int maxLength,
const char *result) {
const char * TEMPLATE= "Running Result: %s";
sprintf_s(resultLineBuffer, maxLength, TEMPLATE, result);
}
void PrintResultToFile(char* exitCode, FILE* resultFile) {
char resultLine[ MAX_ELEMENT_LENGTH ];
GenerateResultLine(resultLine, MAX_ELEMENT_LENGTH, exitCode);
printf("LINE: %s\n",resultLine);
fwrite(resultLine, sizeof(char), sizeof(resultLine), resultFile);
}
Does anyone have any idea why?? Thanks
Code is writing uninitialized data to the file
// Code writes entire buffer to the file,
// even though only the leading bytes are defined via a previous sprintf_s()
fwrite(resultLine, sizeof(char), sizeof(resultLine), resultFile);
// Instead
size_t n = strlen(resultLine);
n++; // If the final `\0` is desired.
if (n != fwrite(resultLine, sizeof(char), n, resultFile)) {
handle_error();
}