论坛: 编程破解 标题: c++文件中读和写的操作问题??? 复制本贴地址    
作者: lwei889 [lwei889]    论坛用户   登录
最近做课程设计,银行代收学校学费系统,需要把一些信息放到文件了,方便操作,但遇到了些问题:
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <fstream.h>
struct student                    //定义结构体变量,用于存取数据
{
char  number[10];      //学号
char  name[10];   //姓名
char  njid[2];   //级别
int    xxid;   //学校id号,有0开始
int    zyid;   //专业id号,有0开始
int    flag;   //交费标志,初始化为0
}stu[2];
void main()
{
    int i;
    FILE *fp;
    fp=fopen("information.txt","r");
    for(i=0;i<2;i++)
{
fread(&stu[i],sizeof(struct student),1,fp);  //读取文件中的内容
    cout<<stu[i].number<<stu[i].name<<stu[i].njid<<stu[i].xxid<<stu //输出读取的内容         
          [i].zyid<<stu[i].flag<<endl;
}
}

问题:我按照上面的结构体,建立了一个文本文件(没有通过程序,直接在windows下,建立)并且输入了相应的内容,但在读取文件的内容使,出现了异常情况,问题出在什么地方?c++能不能读取磁盘上以存在的文件的内容?
information中的内容:
991101 jack 01 1 1 0
991102 mary 01 1 1 0

我该怎么正确读取文件的内容,请给予指点!


[此贴被 子木(lwei889) 在 06月05日22时49分 编辑过]

地主 发表时间: 04-06-05 22:47

回复: lida1818 [lida1818]   论坛用户   登录
异常指的是什么?
没有有调试你的程序,估计是换行符的问题(因为我曾碰到过,所以说一下,txt的换行是两个字符),如果你第一行能正确读出,估计就是了。

B1层 发表时间: 04-06-05 22:58

回复: lwei889 [lwei889]   论坛用户   登录
就是能读出第一行,后面的就不正常,会多出两行内容,还会有一些不明白的数字,还想请教一下,那在建立文件时,换行符应该是怎么样的,能举个例子吗?

B2层 发表时间: 04-06-05 23:19

回复: tetley [tetley]   论坛用户   登录
fread 只是将文本文件中的数据按顺序放入stu中,并不会自动判断空格吧。


B3层 发表时间: 04-06-05 23:49

回复: TomyChen [quest]   版主   登录
    for(i=0;i<2;i++)
{
fread(&stu[i],sizeof(struct student),1,fp);  //读取文件中的内容
    cout<<stu[i].number<<stu[i].name<<stu[i].njid<<stu[i].xxid<<stu //输出读取的内容         
          [i].zyid<<stu[i].flag<<endl;
}

fread()这么强!?能区分结构体,并把读出的内容放到结构中!?

B4层 发表时间: 04-06-06 20:53

回复: lwei889 [lwei889]   论坛用户   登录
用c语言创建和读取文件的例子,

#include<stdio.h>
struct stu
{
char name[10];
int num;
int age;
char addr[15];
}boya[2],boyb[2],*pp,*qq;
main()
{
FILE *fp;
char ch;
int i;
pp=boya;
qq=boyb;
if((fp=fopen("stu_list","wb+"))==NULL)
{
printf("Cannot open file strike any key exit!");
getch();
exit(1);
}
printf("\ninput data\n");
for(i=0;i<2;i++,pp++)
scanf("%s%d%d%s",pp->name,&pp->num,&pp->age,pp->addr);
pp=boya;
fwrite(pp,sizeof(struct stu),2,fp);
rewind(fp);
fread(qq,sizeof(struct stu),2,fp);
printf("\n\nname\tnumber age addr\n");
for(i=0;i<2;i++,qq++)
printf("%s\t%5d%7d%s\n",qq->name,qq->num,qq->age,qq->addr);
fclose(fp);
}

B5层 发表时间: 04-06-07 14:27

论坛: 编程破解

20CN网络安全小组版权所有
Copyright © 2000-2010 20CN Security Group. All Rights Reserved.
论坛程序编写:NetDemon

粤ICP备05087286号