Skip to main content
 首页 » 编程设计

C++ std::ofstream 和 std::ifstream

2022年07月19日39tintown

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 
*/

优秀博文:

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


本文参考链接:https://www.cnblogs.com/hellokitty2/p/16449097.html