首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

大家帮忙看看,关于文件操作的,该怎么解决

2012-02-04 
大家帮忙看看,关于文件操作的#includestdio.h#includestdlib.h#defineNUM100structemployee{charno[5]

大家帮忙看看,关于文件操作的
#include   <stdio.h>
#include   <stdlib.h>
#define   NUM   100
struct   employee
{
char   no[5];                   /*   职工号   */
char   name[8];               /*   姓名       */
char   sex[3];                 /*   性别:男或女   */
int   age;                         /*   年龄       */
int   salar;                     /*   工资       */
}emp[NUM];

int   main()
{
FILE   *fp;
int   n,   i;
if   (   (   fp   =   fopen( "e:\\emp.txt ",   "w ")   )   ==   NULL   )
{
printf(   "can 't   creat   emp.txt   file\n "   );
exit   (   1   );
}

printf(   "Please   input   the   number   of   employee: "   );
scanf(   "%d ",   &n   );
printf(   "input   format:NO.   name   sex   age   salar <Enter> \n "   );
for   (   i   =   0;   i   <   n;   i++   )
{
printf(   "the   %dth   employee: ",   i+1   );
scanf(   "%s%s%s%d%d ",   emp[i].no,   emp[i].name,   emp[i].sex,   &emp[i].age,   &emp[i].salar   );
}
for   (   i   =   0;   i   <   n;   i++   );
fwrite(   &emp[i],   sizeof(struct   employee),   1,   fp   );
fclose(   fp   );

system(   "pause "   );
return   0;
}
输入完成后,我在E盘下打开emp.txt文件看都是0,并不是我输入的结果。
请问怎么做才能在打开文件时看到我输入的结果?

[解决办法]
#include <stdio.h>
#include <stdlib.h>
#define NUM 100
struct employee
{
char no[5]; /* 职工号 */
char name[8]; /* 姓名 */
char sex[3]; /* 性别:男或女 */
int age; /* 年龄 */
int salar; /* 工资 */
}emp[NUM];

int main()
{
FILE *fp;
int n, i;
if ( ( fp = fopen( "e:\\emp.txt ", "w ") ) == NULL )
{
printf( "can 't creat emp.txt file\n " );
exit ( 1 );
}

printf( "Please input the number of employee: " );
scanf( "%d ", &n );
printf( "input format:NO. name sex age salar <Enter> \n " );
for ( i = 0; i < n; i++ )
{
printf( "the %dth employee: ", i+1 );
scanf( "%s%s%s%d%d ", emp[i].no, emp[i].name, emp[i].sex, &emp[i].age, &emp[i].salar );
printf( "%s %s %s %d %d\n ",emp[i].no, emp[i].name, emp[i].sex, emp[i].age, emp[i].salar);
fprintf(fp, "%s %s %s %d %d\n ",emp[i].no, emp[i].name, emp[i].sex, emp[i].age, emp[i].salar);
}
fclose( fp );
system( "PAUSE ");
return 0;
}
[解决办法]
文本显示的话 一般显示字符char
jixingzhong(瞌睡虫·星辰) 做的就是这个步骤

而你是自定义类型的,我做了一下可以的
for ( i = 0; i < n; i++ )
{
printf( "the %dth employee: ", i+1 );


scanf( "%s%s%s%d%d ", emp[i].no, emp[i].name, emp[i].sex, &emp[i].age, &emp[i].salar );
printf( "%s %s %s %d %d\n ",emp[i].no, emp[i].name, emp[i].sex, emp[i].age, emp[i].salar);
fprintf(fp, "%s %s %s %d %d\n ",emp[i].no, emp[i].name, emp[i].sex, emp[i].age, emp[i].salar);
fwrite( &emp[i], sizeof(struct employee), 1, fp );//新加的
}
比如你输入 id huang mal 12 12
由 fwrite( &emp[i], sizeof(struct employee), 1, fp ;得到
id mal c c //12的十六进制是 c

热点排行