c - fwrite 无法正确写入

标签 c windows fwrite

我一直在尝试使用 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/

相关文章:

c++ - 如果应用程序从安装选项启动,则 LoadLibrary 失败,错误代码为 126

c - fwrite 只写入第一个元素并删除所有后续元素

r - 如何在 fwrite() 中指定编码以导出 csv 文件 R?

c - 使用 EOF 多路复用非阻塞套接字 IO

C 服务器和客户端错误地交换 mpz_t 值

regex - 如何使用 powershell 从我的文件名中删除多余的空格?

c++ - 了解 fwrite() 的缓冲行为

c - 想根据用户需要多次调用 fgets()

c - 如果我已经有权访问系统,那么 system() 函数的用途是什么?

c - 如何更改按钮上的光标?