Jump to content
  • Advertisement
Sign in to follow this  
Calin

File reading/writting and STL strings

This topic is 4672 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'm making a utility that will allow me to manipulate file names and content. I started using STL strings because of their ease of use. I want to ask if there is a way of using strings directly with "stdio"/"fstream" libraries without using chars as middle man? If no what would be the easiest method to write a several-page-long string to a file?

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by Calin
... I want to ask if there is a way of using strings directly with "stdio"/"fstream" libraries without using chars as middle man? If no what would be the easiest method to write a several-page-long string to a file?


here is one way:


#include <iterator> // istreambuf_iterator
#include <fstream>
#include <string>

....

typedef std::istreambuf_iterator<char> istrbuf_itr;

...

std::ifstream fin(...);

std::string s((istrbuf_itr(fin)), // note the extra pathness is necessary!
istrbuf_itr());


Which is for unformatted I/O preserves whitespace.

If you want to read a line at time instead use the free-function std::getline, it is not a member function of an iostream.

Share this post


Link to post
Share on other sites
Thanks for your replies! I didn't fully understand snk_kid's
code so I tried this for file writing:


FILE *f = NULL;
f = fopen(path.c_str(),"wb+");
fputs (filestring.c_str(),f);

This works as expected with one small exception: I get a ÿ right at the end of the file. I searched the 'filestring' and there is no 'ÿ' inside.

Share this post


Link to post
Share on other sites
Quote:
Original post by snk_kid
[lol] i just realized you wrote write not read, i'm losing my mind [embarrass].

[smile]



I've solved it. There was a 'ÿ' at the end of that string but for some reason 'cout << filestring' would not display that character. I had to use .find() to track it down.

My final solution:

string NewS(filestring, 0, filestring.size()-1);
FILE *f = NULL;
f = fopen(path.c_str(),"wb+");
fputs (NewS.c_str(),f);

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!