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

时间:2013-09-21 15:47:26

标签: c++ c file ofstream

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

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

感谢。

1 个答案:

答案 0 :(得分:2)

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

#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 *可能更方便,因为string可以很容易地转换为const char *。