c++中对文件操作需要包含头文件<fstream>
文件类型分为两种:
1、文本文件:文件以文本的ASCII码存储在计算机中。
2、二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂。
操作文件的三大类:
1、ofstream 读文件
2、ifstream 读操作
3、fstream 读写操作
读文件:
#include <iostream>
using namespace std;
#include <fstream>
int main()
{
ofstream ofs;
ofs.open("text.txt",ios::out);
ofs << "name:tom" << endl;
ofs.close();
system("pause");
return 0;
}
总结:
文件操作必须包含头文件 fstream
读文件可以利用ofstream,或者发stream类
打开文件时候需要指定操作文件的路径,以及打开方式
利用<<可以向文件中写数据
操作完毕,要关闭文件
写文件:
#include <iostream>
using namespace std;
#include <fstream>
#include <string>
int main()
{
ifstream ifs;
ifs.open("text.txt",ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return 0;
}
//第一种方式
char temp[1024] = { 0 };
while (ifs >> temp)
{
cout << temp << endl;
}
//第二种方式
char loop[1024] = { 0 };
while (ifs.getline(loop, sizeof(loop)))
{
cout << loop << endl;
}
//第三种方式
string buf;
while (getline(ifs, buf))
{
cout << buf << endl;
}
ifs.close();
system("pause");
return 0;
}
总结:
读文件可以利用ifstream,或者fstream类
利用is_open函数可以判断文件是否打开成功
close关闭文件