1.文件操作相关的库

一、filesystem(C++17) 和 fstream

1.std::filesystem::path - cppreference.cn - C++参考手册

std::filesystem::path

表示路径

构造函数:

path( string_type&& source, format fmt = auto_format );

可以用string进行构造,也可以用string进行隐式类型转换。

2.std::filesystem::exists - cppreference.cn - C++参考手册

bool exists( const std::filesystem::path& p );

检查路径是否指向现有的文件系统对象,即对应路径的文件是否存在。

3.std::filesystem::create_directory, std::filesystem::create_directories - cppreference.cn - C++参考手册

bool create_directory( const std::filesystem::path& p );

bool create_directories( const std::filesystem::path& p );

creat_directory创建单个空目录,create_directories递归创建目录。

4.打开文件(IO,ifstream和ofstream)

4.1.写方式打开 ofstream

explicit ofstream (const string& filename, ios_base::openmode mode = ios_base::out); //不传参默认直接覆盖写入
初始化,类似于 open(filename,O_WRONLY | mode);
filename为文件名,mode为打开的方式, std::ios::app 表示以追加方式写入。
ios中相关操作对象:
ios::in :读取文件(ifstream默认模式)
ios::out :写入文件(ofstream默认模式,会覆盖原内容)
ios::app :追加写入(写入内容始终在文件末尾)
ios::ate:打开文件后定位到末尾(可移动指针)
ios::trunc:清空文件内容(ofstream默认行为,与ios::out组合时生效)
简述:
追加方式打开:
std::ofstream ofs(filename, std::ios::out | std::ios::app); (std::ios::out可省略)
效果:不存在就新建,追加写入。 ( std::ios::out 可不写,ofstream自带这个)

隐含行为:如果文件不存在,std::ofstream 会自动创建文件ofstream隐含 O_CREAT

只写且清空方式打开:

std::ofstream ofs(filename, std::ios::trunc);

相当于行为:open(filename, O_CREAT | O_WRONLY | O_TRUNC);

4.2.读方式打开 ifstream

cpp 复制代码
explicit ifstream (const string& filename, 
        ios_base::openmode mode = ios_base::in);//默认只读

以只读方式打开:

std::ifstream ifs(filename);

相当于行为:open(filename, O_RDONLY);

4.3 关闭

cpp 复制代码
void close();

5.读写操作

5.1 读操作

cpp 复制代码
istream& read (char* s, streamsize n);
istream& getline (istream&  is, string& str);

第一个:按指定字节数量读,读到s中。file.read(s,n);

第二个:按行读取,读到str中。std::getline(file,str);

5.2 写操作

用流插入的方式进行写入,和cout一致。

file<<xxx;

6.文件重命名

void rename( const std::filesystem::path& old_p, const std::filesystem::path& new_p );

使用:std::filesystem::rename(old,new);

7.更改工作目录

void current_path( const std::filesystem::path& p );

使用:std::filesystem::current_path(newWorkDir);

相关推荐
汉汉汉汉汉1 小时前
C++11新特性详解:从列表初始化到线程库
c++
楼田莉子3 小时前
C++算法题目分享:二叉搜索树相关的习题
数据结构·c++·学习·算法·leetcode·面试
大锦终3 小时前
【算法】模拟专题
c++·算法
方传旺4 小时前
C++17 std::optional 深拷贝 vs 引用:unordered_map 查询大对象性能对比
c++
Dontla4 小时前
Makefile介绍(Makefile教程)(C/C++编译构建、自动化构建工具)
c语言·c++·自动化
何妨重温wdys4 小时前
矩阵链相乘的最少乘法次数(动态规划解法)
c++·算法·矩阵·动态规划
重启的码农4 小时前
ggml 介绍 (6) 后端 (ggml_backend)
c++·人工智能·神经网络
重启的码农4 小时前
ggml介绍 (7)后端缓冲区 (ggml_backend_buffer)
c++·人工智能·神经网络
雨落倾城夏未凉5 小时前
5.通过拷贝构造函数复制一个对象,假如对象的成员中有个指针类型的变量,如何避免拷贝出来的副本中的该成员之下行同一块内存(等价于默认拷贝构造函数有没有缺点)
c++·后端
雨落倾城夏未凉5 小时前
4.深拷贝VS浅拷贝
c++·后端