Question

I want to write numbers into a file .dat in C++. I create a function, it uses ofstream. It's correct?

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

Thanks.

Was it helpful?

Solution

Yes, it's correct. It can also be simplified, for example:

#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);
}

It may be more convenient in C++, to take const char* rather then char *, because string can readily be converted to const char *.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top