C++ 对文件的最常用操作
☆ 基本概念
- 根据文件中数据的组织方式,可以将文件分为 ASCII 文件 和 二进制文件。
- 前者又称为文本文件或字符文件,后者又称为内部格式文件或字节文件。
- 本文讲解针对 ASCII 文件的基操,具体内容详见代码。
#include <fstream>
#include <string>
#include <iostream>
/*
ifstream 类,从 istream 类派生。用来支持从磁盘文件输入。
ofstream 类,从 ostream 类派生。用来支持向磁盘文件输出。
fstream 类,从 iostream 类派生。用来支持对磁盘文件的输入输出。
*/
int main() {
// ofstream 是从内存到硬盘,ifstream 是从硬盘到内存,其实所谓的流缓冲就是内存空间
// 写文件
std::ofstream outfile1("file.txt", std::ios::out); //定义文件流对象,打开磁盘文件 file.txt
// 此方法与 open 函数作用相同,
// ios::out → 以输出方式打开(没有则创建,这是默认方式),如果有同名文件夹,则将其原有内容全部清空
/* 常用参数
ios::app 以追加的方式打开文件
ios::ate 文件打开后定位到文件尾,ios::app 就包含有此属性
ios::binary 以二进制方式打开文件,缺省的方式是文本方式。
ios::in 文件以输入方式打开(文件数据输入到内存)
ios::out 文件以输出方式打开(内存数据输出到文件)
ios::nocreate 不建立文件,所以文件不存在时打开失败
ios::noreplace 不覆盖文件,所以打开文件时如果文件存在失败
ios::trunc 如果文件存在,把文件长度设为 0
可以用 “ 或 ” 把以上属性连接起来,如 ios::out | ios::binary*/
if (!outfile1) { // 打开失败,outfile 返回值为 0
std::cerr << "open failure" << '\n';
exit(1);
}
std::string content;
std::cout << "输入你想输入文件的内容:\n";
// std::cin >> content; // 只能接收到空格以前
getline(std::cin, content); // 可以接收所有内容
/*文本文件的读写
用插入器( << )向文件输出;
用析取器( >> )从文件输入*/
outfile1 << content; // 向磁盘文件输入内容
outfile1.close(); // 关闭磁盘文件
// 读文件
std::string file{ "file.txt" };
std::ifstream outfile2(file);
if (!outfile1) { // 打开失败,outfile 返回值为 0
std::cerr << "open failure" << '\n';
exit(1);
}
/*
* 注释方法由于循环次数不定,会将最后一个字符串重复输出
std::string str;
std::string lastStr;
for (size_t i = 0; i < 100; ++i) {
outfile2 >> str;
lastStr += (str + " ");
}*/
std::string lastStr;
while (std::getline(outfile2, lastStr)); // 将文件所有内容输出到 lastStr
outfile2.close(); // 关闭磁盘文件
std::cout << lastStr << std::endl;
system("pause");
return 0;
}
最后的效果
文本文件