C方式
#include<stdio.h>
#define F_PATH "d:\\myfile\\file.dat"
char c;
int main(){
FILE*fp=NULL;//需要注意
fp=fopen(F_PATH,"r");
if(NULL==fp) return -1;//要返回错误代码
while(fscanf(fp,"%c",&c)!=EOF)
printf("%c",c); //从文本中读入并在控制台打印出来
fclose(fp);
fp=NULL;//需要指向空,否则会指向原打开文件地址
return 0;
}
C++逐行读取文本
ifstream file;
file.open(strPath, ios::in);
if (!file.is_open())
return;
string strLine;
while (getline(file, strLine))
{
if (strLine.empty())
continue;
//do something
......
}
二进制文件操作
对二进制文件的读写主要用istream类的成员函数read和write来实现。这两个成员函数的原型为
istream& read(char *buffer,int len);
ostream& write(const char * buffer,int len);
#include <iostream>
using namespace std;
#include <fstream>
class Teacher
{
public:
Teacher()
{
}
Teacher(int age,char name[20])
{
this->age = age;
strcpy(this->name,name);
}
void prinfInfo()
{
cout<<"Teacher name:"<<this->name<<" age:"<<this->age<<endl;
}
private:
int age;
char name[20];
};
测试代码
int main()
{
Teacher t1(31,"xiaoming");
Teacher t2(32,"xiaohong");
Teacher t3(33,"xiaohua");
Teacher t4(34,"xiaoxin");
char fname[] = "d:/file2";
fstream fs(fname,ios::binary|ios::out);
if(!fs)
{
cout<<"文件打开失败"<<endl;
}
fs.write((char *)&t1,sizeof(Teacher));
fs.write((char *)&t2,sizeof(Teacher));
fs.write((char *)&t3,sizeof(Teacher));
fs.write((char *)&t4,sizeof(Teacher));
fs.flush();
fs.close();
fstream fs2(fname,ios::binary|ios::in);
if(!fs)
{
cout<<"文件打开失败"<<endl;
}
Teacher tt;
fs2.read((char *)&tt,sizeof(Teacher));
tt.prinfInfo();
fs2.read((char *)&tt,sizeof(Teacher));
tt.prinfInfo();
fs2.read((char *)&tt,sizeof(Teacher));
tt.prinfInfo();
fs2.read((char *)&tt,sizeof(Teacher));
tt.prinfInfo();
fs2.close();
system("pause");
return 0;
}
输出结果:
Teacher name:xiaoming age:31
Teacher name:xiaohong age:32
Teacher name:xiaohua age:33
Teacher name:xiaoxin age:34