简体   繁体   English

为什么fwrite&fread打印垃圾?

[英]Why is fwrite & fread printing garbage?

When The following code is run, why is there extra garbage printed alongside the HALLO string? 当运行以下代码时,为什么在HALLO字符串旁边打印了多余的垃圾?

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *binfile;

    binfile = fopen("binary.bin", "wb+");

    char arr[5] = "HALLO";
    int integer = 1;
    double doub = 1.2345;

    fwrite(arr, sizeof(arr), 1, binfile);
    fwrite(&integer, sizeof(int), 1, binfile);
    fwrite(&doub, sizeof(double), 1, binfile);

    fclose(binfile);

    binfile = fopen("binary.bin", "r");

    char arr2[5];
    int integer2;
    double doub2;

    fread(arr2, sizeof(arr2), 1, binfile);
    fread(&integer2, sizeof(int), 1, binfile);
    fread(&doub2, sizeof(double), 1, binfile);

    printf("%s\n", arr2);
    printf("%d\n", integer2);
    printf("%lf\n", doub2);

    fclose(binfile);
    return EXIT_SUCCESS;
}

Becuase you have not allowed for the null terminator on the string. 因为您不允许在字符串上使用null终止符。

Ok, some more detail. 好的,更多细节。 You have not made it clear what you're trying to do, so let's assume you want to write 5 char bytes. 您还没有弄清楚您要做什么,所以假设您要写入5个char字节。 The problem is that when you read back your 5 chars you read them back into a char array (fine) then try to print that array with no null terminator - not fine. 问题是,当您读回5个字符时,会将它们读回到一个char数组中(精细),然后尝试不使用空终止符打印该数组-不好。

So either read them back into a new array and set 因此,要么将它们读回新数组并设置

newarray[5]=0;

or print it out safe in the knowledge that you have 5 chars 或在知道您有5个字符的情况下安全地打印出来

printf("%5.5s",array);

(something like that anyway) (还是这样)

printf("%s\\n", arr2) interprets arr2 as a pointer to a string, not as a char array. printf(“%s \\ n”,arr2)arr2解释为指向字符串的指针,而不是char数组。 Since your char array does not end with a zero terminator, printf happily prints whatever is stored in the memory locations following the char array. 由于您的char数组不以零终止符结尾,因此printf可以愉快地打印出char数组之后的内存位置中存储的所有内容。

This code snippet should work: 此代码段应工作:

char arr2[5+1];
fread(arr2, sizeof(arr2) - 1, 1, binfile);
arr2[sizeof(arr2) - 1] = '\0';
printf("%s\n", arr2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM