为什么我的 fread returns 是一个空字符串?

How come my fread returns an empty string?

当我将字符串写入文件时,我首先将字符串的长度写入一个 int,然后是字符串本身。这是我的代码:

int wordLength = strlen(words);
fwrite(&wordLength,sizeof(int),1, outputFile);
fwrite(&words,sizeof(char),strlen(words), outputFile);

然而,当我 fread 回来时,我得到一个空字符串。这是我的阅读代码:

int strLength;
fread(&strLength, sizeof(int), 1, f);
char* word = (char*) malloc(strLength*sizeof(char));
fread(&word, sizeof(char), strLength, f);

为什么会这样?

这适用于 Ubuntu:

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

int main(int argc, char **argv)
{

    FILE *outputFile;
    FILE *inputFile;
    char words[] = "This is a series of words";

    int wordLength = strlen(words);

    outputFile = fopen("outputFile", "w");
    if ( outputFile == NULL )
    {
        perror("fopen failed: ");
    exit(1);
    }


    fwrite(&wordLength,sizeof(int),1, outputFile);
    fwrite(words,sizeof(char),strlen(words), outputFile);

    fclose(outputFile);

    inputFile = fopen("outputFile", "r");
    if ( inputFile == NULL )
    {
        perror("fopen(2) failed: ");
    exit(1);
    }

    int strLength = -99;
    fread(&strLength, sizeof(int), 1, inputFile);

    char* buff = (char*) malloc(strLength*sizeof(char));
    fread(buff, sizeof(char), strLength, inputFile);

    buff[strLength] = 0x00;

    printf("Input Str: -->%s<--\n", buff);

}

when I fread it back, I get an empty string. Here is my reading code:
Why is this happening?

fread(&strLength, sizeof(int), 1, f);
char* word = (char*) malloc(strLength*sizeof(char));
fread(&word, sizeof(char), strLength, f);
  1. 代码分配的内存不足。 strLength*sizeof(char) 足以用于文本但不是终止 空字符 来制作 字符串 .

    // char* word = (char*) malloc(strLength*sizeof(char));
    char* word = malloc(strLength + 1u); // add 1
    
  2. fread(&word, ...); 正在尝试将数据读入 word 的地址,而不是刚刚分配的内存。

    // fread(&word, sizeof(char), strLength, f);
    fread(word, sizeof *word, strLength, f);  // drop &
    
  3. 永远不会附加 空字符

    size_t count = fread(word, sizeof *word, strLength, f);
    if (count != strLength) puts("Error");
    else {
      word[strLength] = '[=13=]';
      puts(word);
    }
    

备注: 最好使用 size_t wordLength

检查 malloc() 的 return 值可以生成好的代码。

size_t wordLength = strlen(words);
...
char* word = malloc(strLength + 1);
if (word == NULL) Hanlde_OutOfMemory();

Post 不显示文件 open/closing 的详细信息。代码可能需要rewind(f)在读取数据之前写入。