文件操作需要包含头文件#include
文件类型分为两种:
文本文件:文本以文本的ASCII码形式存储在计算机中
二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能读懂
1、打开文件
ofs.open(“文件路径”,“打开方式”)
2、读或写操作
ofs<<“写入的数据”;
3、关闭文件
ofs.close();
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream ofs;
ofs.open("test.txt", ios::out);
ofs << "姓名:\t张三" << "\n";
ofs << "性别:\t男" << "\n";
ofs << "年龄:\t18" << "\n";
ofs.close();
return 0;
}
注意:路径分为绝对路径和相对路径
打开方式ios::out,若文件不存在则创建文件,若文件已存在,则将原先的内容清除后,写入新的内容。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream ifs;
ifs.open("test.txt", ios::in);
if (ifs.is_open()) {
cout << "文件打开成功\n";
}
else {
cout << "文件打开失败\n";
exit(-1);
}
//读文件
//第一种
//char buf[1024] = { 0 };
//while (ifs >> buf) {
// cout << buf << "\n";
//}
//第二种
//char buf[1024] = { 0 };
//while (ifs.getline(buf,sizeof(buf))) {
// cout << buf << "\n";
//}
//第三种
//string buf;
//while (getline(ifs, buf)) {
// cout << buf << "\n";
//}
//第四种
char c;
while ((c = ifs.get()) != EOF) {
cout << c;
}
ifs.close();
return 0;
}
第一种:
第二种:每次读取一行
第三种:(我喜欢用)
第四种:一次读取一个字符
读取二进制文件
#include<iostream>
using namespace std;
#include<fstream>
int main() {
ifstream ifs;
ifs.open("D:\\1.jpg",ios::binary);
ofstream ofs;
ofs.open("E:\\1.jpg", ios::binary);
unsigned char buf[1024];
int count = 0;
while (!ifs.eof()) {
count++;
ifs.read((char*)&buf, 1024);
ofs.write((char*)&buf, ifs.gcount());
}
cout << count;
ifs.close();
ofs.close();
return 0;
}