C/C++读取文件总结

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
	......
}

C/C++ 文件读取

二进制文件操作
对二进制文件的读写主要用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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值