使用结构进行文件写入 [英] filewrite using structure

查看:57
本文介绍了使用结构进行文件写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include
#include
calc(struct salesdata *salesptr);
struct salesdata{
		char transno[4];
		int salesno;
		int prodno;
		int unit_sold;
		float value_of_sale;
		};
void main()
{

FILE *fp;
struct salesdata salesrec,*ptr;
clrscr();
ptr=fopen("rand.txt","w");
printf("Enter transsaction no: ");
scanf("%3s",salesrec.transno);
fflush(stdin);

printf("Enter salesman no: ");
scanf("%d",&salesrec.salesno);
fflush(stdin);

printf("Enter the product number: ");
scanf("%d",&salesrec.prodno);
fflush(stdin);

printf("Enter unit sold: ");
scanf("%d",&salesrec.unit_sold);
fflush(stdin);

(float)salesrec.value_of_sale=calc(&salesrec);
printf("Value of sale: %f");

ptr=&salesrec;
fwrite(ptr, sizeof(struct salesdata),1,fp);


getch();
}
calc(struct salesdata *salesptr)
{
static float prod_rate[4]={ 12.0, 65.0, 30.0, 20.5 };
salesptr->value_of_sale=(float)salesptr->unit_sold* prod_rate[salesptr->prodno-1];
return salesptr->value_of_sale;
}


我正在将记录写入rand.txt文件.编写工作已完成,但已以编码形式显示.因此,请提供帮助....


I''m writing the record to rand.txt file. Writing is being done but it''s shown in an encoded form. So, please help....

推荐答案

它不是编码形式,而是以二进制数据形式写入文件的.如果您希望将其视为文本,则应将值转换为文本(或字符串).您不能用一个命令来转换结构,就不能将其写入文件,因为没有这样的转换功能,而且结构的大小也无法与文本等效.首先,您可以使用itoa转换int值.要编写文本文件,请查看链接:
http://www.cprogramming.com/tutorial/cfileio.html [
It isn''t in an encoded form but its written to file as binary data. If you would like to see it as text you should convert the values to text (or string). You can''t convert the struct with a one single command and write it to file the way you do because there is no such conversion function and also the size of the struct wouldn''t match the text equivalent. For a start, you can convert int values using itoa. For writing text files, have a look at the link:
http://www.cprogramming.com/tutorial/cfileio.html[^]

Good luck!


帮助什么?您正在将字节数组(您的结构)写入文件中,这就是它的显示方式.如果想要某种文本格式,则需要编写一些序列化例程,该例程会将每个单独的字段转换为文本,并将文本字符串写入文件.但是,请注意,对float值执行此操作可能会导致在读回值时造成精度损失.通常,永远不要使用float来表示货币值.
Help with what? You are writing an array of bytes (your structure) into a file so that is how it will appear. If you want it in some sort of text format then you need to write some serialization routine that will convert each individual field to text and write the text string to your file. However, be aware that doing so for your float value will cause potential loss of precision when reading the values back in. As a general rule you should never use float to represent monetary values.


这篇关于使用结构进行文件写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆