C++编程如何指定文本文件存储路径,将文件保存到指定文件夹
C++ 指定生成文件存储到patch目录的实现方法
你只需先保证patch目录存在,再在open方法中传入带目录前缀的文件路径即可,以下是具体实现:
方法1:C++17及以上版本(跨平台推荐)
使用C++标准库内置的filesystem模块自动创建目录,无需手动提前建文件夹,适配全平台:
#include <iostream> #include <fstream> #include <filesystem> using std::ios; using std::fstream; namespace fs = std::filesystem; int main(){ const std::string patch_dir = "./patch"; // 检测patch目录是否存在,不存在则创建 if (!fs::exists(patch_dir)) { fs::create_directory(patch_dir); } fstream filetext; // 直接指定文件存储到patch目录下 filetext.open(patch_dir + "/usertext.txt", ios::app); // 附加打开失败校验逻辑,更健壮 if (!filetext.is_open()) { std::cerr << "文件打开失败,请检查目录权限" << std::endl; return 1; } filetext << "hello world!"; filetext.close(); return 0; }
注意:使用GCC 8以下版本编译时需要额外加链接参数-lstdc++fs,Clang低版本需加-lc++fs
方法2:兼容旧C++标准版本
如果你的编译环境不支持C++17,可以选择两种方案:
- 手动提前在程序运行目录下创建好
patch文件夹,直接修改open的路径参数即可,代码如下:
#include <iostream> #include <fstream> using std::ios; using std::fstream ; int main(){ fstream filetext; filetext.open("./patch/usertext.txt", ios::app) ; if (!filetext.is_open()) { std::cerr << "打开失败,请确认patch文件夹已存在" << std::endl; return 1; } filetext << "hellow world!" ; filetext.close(); return 0; }
- 用平台专属接口创建目录:
- Windows平台包含
<windows.h>后调用CreateDirectory("./patch", NULL) - Linux/macOS平台包含
<sys/stat.h>后调用mkdir("./patch", 0755)
- Windows平台包含
补充说明
- 路径开头的
./代表程序运行的当前工作目录,如果你需要固定存储位置,也可以直接写绝对路径,比如Windows下写"C:/code/project/patch/usertext.txt",Linux下写"/home/xxx/code/patch/usertext.txt" - 推荐统一用斜杠
/作为路径分隔符,三大主流操作系统都支持,不需要单独适配Windows的双反斜杠\\
内容的提问来源于stack exchange,提问作者taha hdp
相关产品推荐
相关产品推荐

