C++中文件怎样打开和读取文件

如题所述

导入头文件 <fstream.h>
ifstream in("...填写要打开的文件路径");/ /自定义读取文件流的对象.in
if(!in)
cout<<"读取文件失败!"; //判断是否读入成功
ofstream out("..填写要存放读取的文件内容的文件路径");//将读取的内容输入到某个指定的文件中
//最后使用自定义的in时就当cin来用. out就当cout来用就可以了.
in.close(); //关闭读入对象
out.close(); //关闭读出对象
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-10-27
这段代码是一个学生成绩管理系统中的学生成绩结构体、读文件和写文件的函数,是用C语言写的,至于C++,可以适当改写即可
int now_no=0; //初始化计数
struct student{ //定义学生成绩结构体
int no;
char name[20];
char sex[4];
float score1;
float score2;
float score3;
float score4;
float sort;
float ave;
float sum;
};
struct student stu[MAX],*p;
/*...*/
void read() //文件读入
{
FILE *fp;
int i;
fflush(stdin);
if((fp=fopen("stu_grade.txt","r"))==NULL){
printf("找不到stu_grade.txt文件!\n");
system("pause");
exit(0);
}
now_no=0;
for(i=0;i<MAX&&!feof(fp);i++)
{
fscanf(fp,"\t%d\t%s\t%s\t%f\t%f\t%f\t%f\t%f\n",&stu[i].no,stu[i].name,stu[i].sex,&stu[i].score1,&stu[i].score2,&stu[i].score3,&stu[i].score4,&stu[i].ave,&stu[i].sum);
now_no++;
}
fclose(fp);
printf("保存的在文件stu_grade.txt中的所有信息已经读入!\n");
system("pause");
system("cls");
}//read();

void save() //数据保存
{
FILE *fp;
int i;
if((fp=fopen("stu_grade.txt","w"))==NULL){
printf("\n保存失败!");
exit(0);
}
for(i=0;i<now_no;i++)
fprintf(fp,"\t%d\t%s\t%s\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n",stu[i].no,stu[i].name,stu[i].sex,stu[i].score1,stu[i].score2,stu[i].score3,stu[i].score4,stu[i].ave,stu[i].sum);
fclose(fp);
printf("\n通讯录已保存在stu_grade.txt中!\n");
system("pause");
system("cls");
}//save();本回答被提问者采纳
第2个回答  2011-05-19
如果你用CFile类的话,会有一个Seek()方法,去到你想处理的位置,文件末尾的话用file.Seek(0,CFile::end)就可以了。用FILE*的话,也有一个seek()方法,用法差不多的。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网