Sign-up....

关于fwrite的问题

#include <stdio.h>

#include "process.h"

void main()

{FILE *fp;

int i=10;

float f=12.23;

char ch[5]="name";

if(!(fp=fopen("test","wb")))

{printf("cannot open.\n");

exit(1);

}

fwrite(&i,sizeof(int),1,fp);

//fwrite(&f,sizeof(float),1,fp);

//fwrite(&ch,sizeof(ch),1,fp);

fclose(fp);

}

以上代码是一本书上的,可我用VC编译执行后,在所生成的文件中数字为什么是乱码?把test改为test.txt也没用。总之用fwrite输出数字时总是不是自己所想的结果。

[377 byte] By [msdn] at [2007-8-14 20:05:17]
# 1 Re: 关于fwrite的问题

试一下下面的代码

#include <stdio.h>

#include "process.h"

main()

{

FILE *fp;

char ch[5]="name";

if(!(fp=fopen("test.txt","wb")))

{

printf("cannot open.\n");

exit(1);

}

fwrite(ch,sizeof(char),5,fp);

fclose(fp);

}

5420 at 2005-6-19 19:44:20 >
# 2 Re: 关于fwrite的问题

#include <stdio.h>

#include "process.h"

main()

{

FILE *fp;

int i[5]={'1','2','3','4','5'};

char ch[5]="name";

if(!(fp=fopen("test.txt","wb")))

{

printf("cannot open.\n");

exit(1);

}

fwrite(i,sizeof(int),5,fp);

fclose(fp);

}

5420 at 2005-6-19 19:49:53 >
# 3 Re: 关于fwrite的问题

熏衣草的那段代码是没问题,但还是输入字符嘛,要向文件中输入数字类信息呢?是在输入数字类信息出现的乱码。

dcbeyond2005 at 2005-6-19 19:50:13 >
# 4 Re: 关于fwrite的问题

因为看到的是ascii码

s_topman at 2005-6-19 19:55:52 >
# 5 Re: 关于fwrite的问题

fwrite(&i,sizeof(int),1,fp);

在写文件时,用的整形数的内码非ASCII码,当然是乱码了

keiy at 2005-6-19 19:57:40 >
# 6 Re: 关于fwrite的问题

#include <stdio.h>

#include "process.h"

main()

{

FILE *fp;

int i = 10;

if(!(fp=fopen("test.txt","wb")))

{

printf("cannot open.\n");

exit(1);

}

fwrite(&i,sizeof(int),1,fp);

fclose(fp);

}

其实数字已经写到文件中去了,只是ASC码值为那个数字的是个你说的乱码,你可以试一下别的数

最好拿一张ASC码表对着试

5420 at 2005-6-19 19:58:05 >
# 7 Re: 关于fwrite的问题

呵呵....楼上的就是这个意思了!

5420 at 2005-6-19 19:58:59 >
# 8 Re: 关于fwrite的问题

因为你查看是安字符文件查看的,所以当写入数字时是乱码

s_topman at 2005-6-19 20:07:17 >
# 9 Re: 关于fwrite的问题

知道了,在文件的是ASCII码,但我要是输入年龄,编号等,要在文件中显示数字怎么办啊?难道要把数字以字符形式写入吗?

dcbeyond2005 at 2005-6-19 20:43:43 >
# 10 Re: 关于fwrite的问题

用fprintf(fp,"%d",i);

mefit at 2005-6-19 20:51:49 >
# 11 Re: 关于fwrite的问题

putw()专门的写入数据的函数

类似的,有

getw(),一个专门从文件中读取数据的函数

注意,上面的两个函数只能用于int型,每次只能存或读一个数据!!

jixingzhong at 2005-6-20 9:04:09 >
# 12 Re: 关于fwrite的问题

I see.谢谢大家

dcbeyond2005 at 2005-6-20 14:30:34 >
# 13 Re: 关于fwrite的问题

还有怎么结帖啊?

dcbeyond2005 at 2005-6-20 14:44:08 >
# 14 Re: 关于fwrite的问题

也可以在fwrite前用sprintf()把数字转成字符。

nana_2005 at 2005-6-20 15:24:51 >
# 15 Re: 关于fwrite的问题

还有怎么结帖啊?

-->点上面的管理

keiy at 2005-6-20 15:41:47 >

C/C++

All Classified