一、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
explicit ifstream (const string& filename, ios_base::openmode mode = ios_base::in);//默認只讀
以只讀方式打開:
std::ifstream ifs(filename);?相當于行為:open(filename, O_RDONLY);
4.3 關閉
void close();
5.讀寫操作
5.1 讀操作
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);