我有一些代码将char *
写入二进制文件,如下所示:
FILE *fp = fopen(path, "wb");
if (fp == NULL) {
printf("Failed to open file at path: %s. %s\n", path, __PRETTY_FUNCTION__);
return;
}
fwrite("Hello", 6, 1, fp);
问题在于,当我从那个文件中读取时:
FILE *fp = fopen(path, "rb");
if (fp == NULL) {
printf("Failed to open file at path: %s. %s\n", path, __PRETTY_FUNCTION__);
return;
}
char *str;
fread(str, 6, 1, fp);
printf("Got str: %s\n", str);
我得到不同的结果,例如Oello
或Mello
。到底是怎么回事?
答案 0 :(得分:1)
此代码不正确:
char *str;
fread(str, 6, 1, fp);
printf("Got str: %s\n", str);
char *str;
创建未初始化的字符指针。它所指向的记忆在哪里?
char str[ 7 ];
fread(str, sizeof( str ) - 1, 1, fp);
str[ sizeof( str ) - 1 ] = '\0';
printf("Got str: %s\n", str);
会更好,但它仍然不会检查fread()
的返回值,以确保实际读取数据。
答案 1 :(得分:0)
您尚未为str
char *str ; // You haven't allocated memory for it , Do
str=malloc(6*sizeof *str);
然后做
fread(str, 6, 1, fp);
此外,如果在同一翻译单元中进行写入和读取,则应该执行
fclose(fp); // to flush the output buffer and close the file descriptor
从文件中读取