Help heroes a file output, and other online.

Category: C/C++ -> C Author: q770454662 Date: 2013-03-09 20:09:29
 
q770454662
2013-03-09 20:09:29
My one source as follows:
# include <stdio.h>
# define NUM 5
struct goods_inf
{
int no;
char name [15];
float price;
int quan;
; float saleroom;
} gds [NUM];

void save (void)
{
FILE * fp ;
int i;
if ((fp = fopen ("sale_list.txt", "w")) == NULL)
; {
printf ("can'n open file \ n");
return;
}
for (i = 0; i <NUM; i + +)
if (fwrite (& gds [i], sizeof (struct goods_inf), 1, fp)! = 1)
printf ("file write error. \ n");
fclose (fp);
}
static void force_fpf ()
{
float x, * y; / * Just declares two variables * /
; y = &x; / * Forces linkage ; of FP formats * /
x = * y; / * Suppress warning message about x * /
}

main ()
{
int i;
; float total = 0;
FILE * fp;

for (i = 0; i <NUM; i + +)
{
scanf ("% d% s% f% d", & gds [i ]. no, gds [i]. name, & gds [i]. price, & gds [i]. quan);
gds [ i]. saleroom = gds [i]. price * gds [i]. quan;
total + = gds [i]. saleroom;
}
save ();
if ((fp = fopen ("sale_lis", "r")) == NULL)
{
printf ("can't open file. \ n");
; return;
}
/ * fwrite (& total, sizeof (float), 1, fp); * /
printf ("\ n gd_id gd_name gd_price gd_quan gd_slrm \ n");
for (i = 0; i < ; NUM; i + +)
{
fread (& gds [i], sizeof (struct goods_inf), 1, fp);
printf ("%-8d%-16s%-16.2f%-16d%-16.2f \ n", gds [i]. no, gds [i]. name, gds [i]. price, gds [i]. quan, gds [i]. saleroom);
}
; fclose (fp);
}
inputs are:
1001 soap 5.0 100
1002 towel 15.0 120
1003 sock 4.5 200
1004 shirt 25.0 200
1005 shoe 80.0 80

output the result is this:
; gd_id gd_name gd_price gd_quan ; gd_slrm
4096 = Fap 5.00 100 500.00
1002 towel 15.00 120 1800.00
1003 sock ; 4.50 200 900.00
1004 shirt ; 25.00 200 5000.00
1005 shoe 80.00 80 6400.00

4096 ; = Fap these two values ​​is how it was. I trace debugging gds [0] is the value 1001 soap 5.00 100 500 ah.
baolong001
2013-03-09 20:12:52
w + b, rb
because you use sizeof (struct) = representing the number of bytes, not accounting for the number of characters
subifish
2013-03-09 20:27:37
you use rb try
sc199012
2013-03-09 20:30:14
fread / fwrite to read and write files in binary mode operation documents,
otherwise error-prone ....
hbruyi_ccn
2013-03-09 20:34:46
I try to use your program too, in addition to the two open your file names are different than the results entirely correct, no problem.
r.lue
2013-03-09 20:45:27
in text mode, open: fopen (filename, "r"); fprintf (...), fscanf (...)

opened in binary mode: fopen (filename, "rb"); fread (), fwrite ()

a1018856347
2013-03-09 20:56:41
strange, on another machine on the same TC environment compile and run correctly. Then copy the files back to overwrite the original file to run normal again.