1.初步使用写文件
在C++中对文件进行操作必须包含头文件。
对文件操作的类:
fstream:可读可写操作
ifstream:只能读操作
ofstream:只能写操作
简单案例:
#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
ofstream fd;//创建流对象
fd.open("zby.txt");//打开文件
fd<< "aaaaaaaaaaa";
fd.close();//关闭文件
return 0;
}
2.打开方式
文件的打开方式:
ios::in 为读文件打开方式
ios::out 为写文件打开方式
ios::ate 初始位置文件尾
ios::app 写文件尾追加
ios::trunc 若文件存在先删除,在创建
ios::binary 二进制方式打开
#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
ofstream fd;//创建流对象
fd.open("zby.txt",ios::app);//打开文件如果没有会自动创建,
//fd.open("zby.txt", ios::in|ios::out|ios::trunc )//可读可写可创建
fd<< "aaaaaaaaa";
fd<< "bbbbbbbbbbb";//追加在上一行后面
fd.close();//关闭文件
return 0;
}
3读文件
案例1:
#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
ifstream fd("zby.txt", ios::in);
if (!fd.is_open()){
cout << "文件不存在" << endl;
}
char arr[1024] = { 0 };
while (fd >> arr){
cout << arr << endl;
}
fd.close();
return 0;
}
案例2:
#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
ifstream fd("zby.txt", ios::in);
if (!fd.is_open()){
cout << "文件不存在" << endl;
}
char arr[1024] = { 0 };
while (fd.getline(arr, sizeof(arr))){//按行读取
cout << arr << endl;
}
fd.close();
return 0;
}
案例3:
#include<iostream>
#include<string>
#include<fstream>//包含头文件
using namespace std;
int main()
{
ifstream fd("zby.txt", ios::in);
if (!fd.is_open()){
cout << "文件不存在" << endl;
}
string arr;
while (getline(fd, arr)){
cout << arr << endl;
}
fd.close();
return 0;
}
END.