C++文件输入输出

参考博文:https://blog.csdn.net/houbincarson/article/details/136327765

/*
文件输入输出fstream
有三个文件流类:
std::ifstream:用于从文件中读取数据的输入流对象。
std::ofstream:用于向文件中写入数据的输出流对象。
std::fstream:用于读写文件的输入输出流对象。
*/
#include<fstream>
#include<iostream>
using namespace std;
int main(){
	ofstream outputFile;//写入
	outputFile.open("fileOI.txt");
	if(outputFile.is_open()){//是否能打开文件
		/*
		如果文件不存在,则会创建。
		如果存在,则会清空原有内容。
		*/
		outputFile<<"Hello, World!"<<endl;//将文本写入文件
		outputFile<<"START TO STUDY!"<<endl;
	}else{
		cout<<"Unable to open the file.\n";//无法打开文件
		//因为无法打开,实际上也无需关闭
	}
	outputFile.close();//关闭文件
	
	//写入模式修改为追加
	outputFile.open("fileOI.txt", ios::app);//append
	if(outputFile.is_open()){//是否能打开文件
		/*
		如果文件不存在,则会创建。
		如果存在,则会追加到后面。
		*/
		outputFile<<"Hello, World!"<<endl;//将文本写入文件
		outputFile<<"START TO STUDY!"<<endl;
	}else{
		cout<<"Unable to open the file.\n";//无法打开文件
		//因为无法打开,实际上也无需关闭
	}
	outputFile.close();//关闭文件
	
	//读取
	ifstream inputFile("fileOI.txt");
	if(inputFile.is_open()){//是否能打开文件
		//如果文件不存在,则会无法打开,不会创建新文件。
		string line;
		while(getline(inputFile, line)){
			cout <<line <<endl;
		}
	}else{
		cout<<"Unable to open the file.\n";//无法打开文件
		//因为无法打开,实际上也无需关闭
	}
	inputFile.close();//关闭文件
	
	//复制文件,通过逐字节输入获取,逐字节输出到文件
	ifstream source("fileOI.txt", ios::binary);
	ofstream destination("destination.txt", ios::binary);
	if(!source || !destination){
		cout << "Unable to open the file.\n";
		return 1;
	}
	char ch;
	while(source.get(ch)){
		destination.put(ch);
	}
	source.close();
	destination.close();
	cout << "File copied successfully.\n";
	
	
	return 0;
}

posted @ 2024-07-02 08:42  Danlis  阅读(1)  评论(0编辑  收藏  举报