0
点赞
收藏
分享

微信扫一扫

C++——读写文件入门

小月亮06 2022-03-25 阅读 87
c++

一.写文件

1.首先要导入头文件<fstream>

2.创建输出流对象

ofstream ofs;

3.打开文件 ofs.open("c++.txt",ios::out);

第一个参数传文件的相对路径或者绝对路径,第二个参数传打开方式;

4.写入要写入的数据;

ofs<<"姓名:张三" <<endl;

ofs<<"性别:男"<<endl;
ofs<< "年龄: 18"<<endl;        

5.关闭文件 ofs.close();

代码示例:

#include<iostream>
#include<string.h>
#include<fstream>
using namespace std; 
int main(){
	
	ofstream ofs;
	
	ofs.open("c++.txt",ios::out);
	
	ofs<<"姓名:张三" <<endl;
	ofs<<"性别:男"<<endl;
	ofs<< "年龄: 18"<<endl;
	
	ofs.close(); 
} 

二.读文件

1.首先要导入头文件<fstream>

2.创建对象

ifstreaim ifs;

3.打开文件 ofs.open("c++.txt",ios::in);

第一个参数传文件的相对路径或者绝对路径,第二个参数传打开方式;

并判断是否打开        if(!ifs.is_open())        //is_open()返回的是一个bool

4.读数据(四种)

  第一种

string buf;
	while(getline(ifs,buf))
	cout<<buf<<endl;	

第二种

char buf[1024] = {0};
	while(ifs>>buf)
	cout<<buf<<endl;

 第三种

char buf[1024] = {0};
	while(ifs.getline(buf,sizeof(buf))
	cout<<buf<<endl;

 第四种

char c;
	while((c = ifs.get())! = EOF)
	cout << c;

5.关闭文件 ifs.close();

代码示例:

#include<iostream>
#include<string.h>
#include<fstream>
using namespace std; 
int main(){
	
	ifstream ifs;	
	
	ifs.open("c++.txt",ios::in);
	
	if(!ifs.is_open())
	cout<<"文件读取失败"<<endl;
	
	string buf;
	while(getline(ifs,buf))
	cout<<buf<<endl;	
	/*
	char buf[1024] = {0};
	while(ifs>>buf)
	cout<<buf<<endl;
	
	char buf[1024] = {0};
	while(ifs.getline(buf,sizeof(buf))
	cout<<buf<<endl;
	
	char c;
	while((c = ifs.get())! = EOF)
	cout << c;
	
	*/
	
	ifs.close(); 
} 
举报

相关推荐

C++读写文件

c++的文件读写

c++文件的读写

[C++]文件读写操作

c++读写文件操作

C++难点十二:读写文件

0 条评论