fread和fwrite的问题

0 views
Skip to first unread message

Xiaojun Deng

unread,
Oct 10, 2008, 7:46:02 AM10/10/08
to Linux小组
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();
}

贾孟树

unread,
Oct 10, 2008, 9:24:35 AM10/10/08
to Xiaojun Deng, Linux小组


2008/10/10 Xiaojun Deng <xjde...@gmail.com>
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();
    //jeasun add 
      getchar();   
   return 0;
     // add end
}

以上代码在我这里运行正常  输出helloworld  运行一次多一行
编译 运行环境    WinXP  Dev-c++4.9.9.2
 

Xiaojun Deng

unread,
Oct 10, 2008, 9:40:47 AM10/10/08
to 贾孟树, Linux小组
On Fri, 2008-10-10 at 21:24 +0800, 贾孟树 wrote:
>
>
> 2008/10/10 Xiaojun Deng <xjde...@gmail.com>
> fread和fwrite是用来写二进制的文件的,如果用fwrite写了的文件为什

thanks for your correction.
我的意思是用write_info生成了test这个文件后, 修改源代码, 即main函数变成
int main()
{
read_info();
return 0;
}
重新编译运行, 为什么这时候读取test文件得不到任何东西呢?
>
>

Américo Wang

unread,
Oct 10, 2008, 11:32:36 AM10/10/08
to Xiaojun Deng, 贾孟树, Linux小组
On Fri, Oct 10, 2008 at 09:40:47PM +0800, Xiaojun Deng wrote:
>
>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."

Reply all
Reply to author
Forward
0 new messages