Jump to content
  • Advertisement
Sign in to follow this  

write txt to file

This topic is 4422 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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;


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

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

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!