ofstream- 将元素写入文件 - C++

ofstream- Writing an element into a file - C++

本文关键字:文件 C++ 元素 ofstream-      更新时间:2023-10-16

我想将数字写入.dat C++的文件。我创建了一个函数,它使用流。对吗?

void writeValue(char* file, int value){
ofstream f;
f.open(file);
if (f.good()){
    f<<value;
}
f.close(); 
}

谢谢。

是的,这是正确的。它也可以简化,例如:

#include<fstream>
#include<string>
using namespace std;
void writeValue(const char* file, int value){
        ofstream f(file);
        if (f) 
            f<<value;
}
int main()
{
    string s = "text";
    writeValue(s.c_str(), 12);
}

在C++中,使用 const char* 而不是 char * 可能更方便,因为字符串可以很容易地转换为 const char *。