1.创建文件流
创建文件流需要包含头文件
#include
创建文件输入流对象
ofstream file;
创建文件输出流对象
ifstream file;
2.写入文本文件
1.首先创建文件输出流对象
2.使用.open()打开文件 括号中可以填string类型变量。
不重写文件内容,内容追加到末尾:file.open(R”(D:\MySQL\test.txt)”,ios::app);
用file.is_open()函数判断文件是否打开成功
3.使用输出流对象写内容
4.使用.close()关闭输出流对象
文件路径的三种写法:
- string path=”D\data\test.txt”; ‘/’需要转义 //
- R”(D:\MySQL\test.txt) 原始字面量 c++11 标准
- D:/MySQL/test.txt 斜杆反着写
#include
#include
using namespace std;
int main(){
ofstream file;
string path="D\\data\\test.txt";
file.open(path);
file.open(path,ios::app);
file<<"My name is Yang";
file.close();
return 0;
}
3.读取文本文件
1.首先创建文件输入流对象
2.使用.open()打开文件 路径写法同上
3.使用输入流对象读文件
4.使用.close()关闭输出流对象
#include
#include
#include
using namespace std;
int main(){
ifstream file;
file.open(R"(D:\MySQL\test.txt)",ios::app);
if(file.is_open()==false){
cout<<"文件打开失败"<<endl;
}else{
cout<<"文件打开成功"<<endl;
}
string str;
while(getline(file,str)){
cout<<str<<endl;
}
while(file>>str){
cout<<str<<endl;
}
file.close();
return 0;
}
Original: https://blog.csdn.net/weixin_51169222/article/details/128322861
Author: 萨达大
Title: C++文件操作
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/788275/
转载文章受原作者版权保护。转载请注明原作者出处!