Sign in to follow this  
derek7

write txt to file

Recommended Posts

I wanna write int variable to .txt file. if I use << operator ,all is ok. But If I wanna use write method,how to do? another question: if I write float to binary file, how to read back? float f = 12.3f; ofstream of("floatvalue.binary") of.write((const char*)&f, sizeof(float)); of.close(); how to restore the value, because the value in floatvalue.binary is something like this: 00 00 41 46

Share this post


Link to post
Share on other sites
If you want to write an int to a file with the write method, you do it like this:

file.write((char*)&fooInt, sizeof(int));


Edit: OHhhhh, I see what you're asking. If you want to write TEXT using the write method, you need to look up the ASCII keyword for the number you want to write, so you'd need to do and int to ascii conversion for it (there's a non-standard itoa() function for that).

Knowing how an x86 stores floats will help you with floats. I belive you can just treat them like ints though, and they will work.

[Edited by - Drakkcon on May 16, 2006 9:39:51 PM]

Share this post


Link to post
Share on other sites
you can read the float back the same way you wrote it

file.write((char*)&fooFloat, sizeof(float)); // write to file

file.read((char*)&fooFloat, sizeof(float)); // read back from file

Note that the float should not be casted to (const char*) but rather (char*)

if you want to write the float to file so that you can recognize the number when you open the file, you can try something like this:

#include <string>
#include <fstream>
#include <sstream>
using namespace std;

int main()
{
float FooFloat = 12.34;
std::stringstream convert;
std::string StrFloat;

// convert float to string...
convert << FooFloat;
convert >> StrFloat;

ofstream of("floatvalue.txt");

//of.write(StrFloat.c_str(), StrFloat.length());
of << StrFloat;

of.close();

return 0;
}




Reading the value back from file and convert it back to float type:

...
stringstream convert;
float FooFloat;
string StrFloat;

ifstream fin("floatvalue.txt");
getline(fin, StrFloat);
fin.close();

convert << StrFloat;
convert >> FooFloat;
cout << FooFloat << endl;
...


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this