C++ std::ofstream 和 std::ifstream 和 文件操作

1. 简介

C++中对文件进行读写的。

2. 使用Demo

复制代码
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>

using namespace std;

static constexpr char FILE_PATH[] = "1.txt";

int std_ofstream_test(void) {
    int tid = 1122;
    std::string path = "1.txt";
    std::string s_val = "/proc/" + std::to_string(tid) + "/comm";

    std::ofstream out(path.c_str());
    if (!out) {
        cout << "error" << endl;
        return -1;
    }
    out.write(s_val.c_str(), s_val.length());
    out.close();

    return 0;
}


int std_ifstream_test(void) {
    std::string line;
    char *buf = new char[64];

    strcpy(buf, FILE_PATH);
    std::ifstream in(buf);
    if (!in) {
        cout << "error" << endl;
        delete []buf;
        return -1;
    }
    getline(in, line);
    cout << line << endl;
    
    in.close();
    delete []buf;

    return 0;
}

int main()
{
    std_ofstream_test();
    std_ifstream_test();

    return 0;
}

/*
$ g++ -std=c++11 file_write.cpp -o pp
$ ./pp
/proc/1122/comm
$ cat 1.txt
/proc/1122/comm
*/
复制代码

 

3. C++11写文件

复制代码
#include <iostream>
#include <fstream> 

bool file_write_test()
{
    int tid = 1234; //gettid();
    int val = 119;
    std::string s_path = "test.txt";
    std::string s_val = "hello " + std::to_string(tid) + " " + std::to_string(val);

    std::ofstream out(s_path.c_str());
    if (!out) {
        return false;
    }
    out.write(s_val.c_str(), s_val.length());
    out.close();
    
    return true;
}

int main()
{
    file_write_test();
    return 0;
}

/*
$ g++ file_rw.cpp -o pp -std=c++11
$ cat test.txt 
hello 1234 119
*/
复制代码

 

 

优秀博文:

如何使用c++中file stream:https://www.jianshu.com/p/e9fdc4cd3e0f

posted on   Hello-World3  阅读(2252)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2017-07-05 gtk_init()

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示