您的位置:首页 > 编程语言 > C语言/C++

C++ 文件操作fstream -- filesystem遍历目录

2020-07-29 22:25 197 查看

文件打开方式

ios::in   	// 读取的方式打开。如果文件不存在,则打开出错。
ios::out  	//  写入的方式打开,文件不存在就新建一个,文件存在就清除所有内容
ios::app	// 以追加的方式打开文件 不存在 则新建
ios::ate 	 // 追加的方式打开文件	文件不存在则打开出错
ios::trunc   // 打开时清除所有数据
iso::binary  //二进制方式打开文件
ios::nocreate: //不建立文件,所以文件不存在时打开失败
ios::noreplace://不覆盖文件,所以打开文件时如果文件存在失败

文件流操作类

ofstream
文件流输出
ifstream
文件流输入

1.文件写入操作

// 入参是文件的路径+名称
void fileWrite(string &name){
ofstream f(name,ios::app);
if(!f.eof()) {
f<<"this is a test text!";
//f.write("this is a write text!",30);
}
f.close();
return ;
}

2.文件读取操作

// 入参是文件的路径+名称
void fileRead(string &name){
ifstream f;
f.open(name,ios::in);
while(f.good() && !f.eof()){
string temp;
getline(f,temp);
cout<<temp<<endl;
// read
char temp2[21];
f.read(temp2,20);
cout<<"read content:"<<temp2<<endl;
}
f.close();
return ;
}

3.文件指针移动操作

seekg() tellg()
seek 设置文件指针的位置
g get
p put
seekp() tellp()
void moveFilePointer(string &name){
ifstream f(name);
f.seekg(-10,ios::end);  // 移动到文件结尾前
while(f.good() && !f.eof()){
string temp;
getline(f,temp);
cout<<temp<<endl;
}
f.seekg(0,ios::beg); // 移动到文件开头
while(f.good() && !f.eof()){
string temp;
getline(f,temp);
cout<<temp<<endl;
}
f.close();
return ;
}

4.获取文件指针的位置

void getTellg(string &name){
ifstream f(name);
//f.seekg(-100,ios::end);  // 移动到文件结尾前
while(f.good() && !f.eof()){
string temp;
cout<<f.tellg()<<" : ";
getline(f,temp);
cout<<temp<<endl;
}
}

5.计算文件大小

// 返回的单位是Kb
streampos calcFileSize(string &name)  {
ifstream f(name);
f.seekg(0,ios::end);
streampos sp = f.tellg();
return sp;
}

6.遍历目录下的所有文件

#include <iostream>
#include <filesystem>
#include <string>

using namespace std;
using namespace std::filesystem;

void circlePath(string &name) {
path p(name);
if (!exists(name)) {
cerr << "文件不存在" << endl;
return;
}
directory_entry entry(name);
if (file_type::directory == entry.status().type()) {
directory_iterator list(name);
for (auto& it : list) {
if (it.status().type() == file_type::directory) {
string str = it.path().string();
circlePath(str);
}else
cout << it.path().filename() << endl;
}
}
return;
}

// 测试
int main()
{
string str("D:\\Go");
circlePath(str);
return 0;

}

7.修改文件名称

void updateFileName(string &name) {
path p(name);
if (!exists(name)) {
cerr << "文件不存在" << endl;
return;
}
string newName;
newName+=p.parent_path().string() += p.stem().string() +'2'+p.extension().string();
string oldName(p.string());
cout << "oldName:" << oldName << endl;
cout << "newName:" << newName << endl;
cout << rename(oldName.c_str(), newName.c_str()) << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: