我一直在尝试使用 fwrite()
将一个简单的字符串写入 C 语言的文件中。
当我将一个简单的字符串定义为:
char str[]="Hello World!";
并将其写入文件:
fwrite(str, sizeof(char), sizeof(str), fp);
一切似乎都运行良好。
但是当我使用 sprintf_s
创建自定义字符串时,我得到的输出文件是:
畒湮湩湁祬敺浉条硥湯椠杭〰⸱灪㩧爠
虽然 printf
func 会正确打印字符串
完整代码:
#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);
}
有人知道为什么吗? 谢谢
最佳答案
代码正在将未初始化的数据写入文件
// 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();
}
关于c - fwrite 无法正确写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20037191/