比如这段代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct made {
int a;
char *name;
} item;
void read_info()
{
FILE *fp = fopen("./test", "rb");
item tmp;
while (fread(&tmp, sizeof(item), 1, fp) == 1) {
printf("%s\n", tmp.name);
}
fclose(fp);
}
void write_info()
{
FILE *fp;
if ((fp = fopen("./test", "a")) == NULL) exit(1);
item *p = (item *)malloc(sizeof(item));
p->a = 111;
p->name = (char *)malloc(sizeof(char) * 10);
strcpy(p->name, "helloworld");
if (fwrite(p, sizeof(item), 1, fp) != 1) {
exit(1);
}
fclose(fp);
}
int main()
{
write_info(); /* 第一次只运行write_info, 生成test文件, 第二次注释掉
这句,只运行read_info, 读文件, 为什么读不到任何信息呢? */
read_info();
}
fread和fwrite是用来写二进制的文件的,如果用fwrite写了的文件为什么不能用
fread读出来呢?
比如这段代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct made {
int a;
char *name;
} item;
void read_info()
{
FILE *fp = fopen("./test", "rb"); // 最好把这两句位置倒一下,
item tmp; // 而且你没有对这个指针做判断
while (fread(&tmp, sizeof(item), 1, fp) == 1) {
printf("%s\n", tmp.name);
}
fclose(fp);
}
void write_info()
{
FILE *fp;
if ((fp = fopen("./test", "a")) == NULL) exit(1);
item *p = (item *)malloc(sizeof(item));
p->a = 111;
p->name = (char *)malloc(sizeof(char) * 10);
strcpy(p->name, "helloworld");
if (fwrite(p, sizeof(item), 1, fp) != 1) {
exit(1);
}
fclose(fp);
}
int main()
{
write_info(); /* 第一次只运行write_info, 生成test文件, 第二次注释掉
这句,只运行read_info, 读文件, 为什么读不到任何信息呢? */
read_info();
return 0;
}
thanks for your correction.
我的意思是用write_info生成了test这个文件后, 修改源代码, 即main函数变成
int main()
{
read_info();
return 0;
}
重新编译运行, 为什么这时候读取test文件得不到任何东西呢?
>
>
因为你写进去的是char*指针。
写入指针的值下次运行再读就很可能不对,因为那个指针未必就指在同一个位置。
--
"Sometimes the only way to stay sane is to go a little crazy."