我有一个float数组,有 189 个元素(从索引 0 到索引 188)。我在将此数组写入文件时遇到问题。假设第一个元素是 45.6,第二个元素是 67.9,我希望我的输出文件如下所示:
0, 45.6\n1, 67.9\nRun Code Online (Sandbox Code Playgroud)\n等等。我已经尝试了下面所示的函数,结果是我的输出文件中有奇怪的字符。
\n0, 45.6\n1, 67.9\nRun Code Online (Sandbox Code Playgroud)\n我得到一个像这样的输出文件:
\n\xef\xbf\xbd\'\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xdb\xbdl^\xef\xbf\xbd\xef\xbf\xbd(\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd!>\nRun Code Online (Sandbox Code Playgroud)\n我也尝试过设置sizeof(slidingCorrelator)为 189,但这也没有帮助。
该fwrite()函数写入二进制数据。您想要编写的是值的人类可读(即文本)表示形式float,而不是二进制表示形式。
您可以使用以下方法执行此操作fprintf():
float slidingCorrelator[N];
FILE *fp;
// ... fill the array somehow ...
fp = fopen("CorrelationResult.txt", "w");
// check for error here
for (unsigned i = 0; i < N; i++) {
fprintf(fp, "%d, %f\n", i, slidingCorrelator[i]);
// check for error here too
}
fclose(fp);
Run Code Online (Sandbox Code Playgroud)
不要忘记检查这些函数的返回值以检测错误。有关更多信息,请参阅: