File reading/writting and STL strings

Started by
5 comments, last by Calin 18 years, 3 months ago
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?

My project`s facebook page is “DreamLand Page”

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.
Off the top of my head:

fin.write(&*str.begin(), str.size());


You can use std::getline to read a string
std::getline(fin, str, '\n');
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
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.

My project`s facebook page is “DreamLand Page”

I can't see why that would give you a ÿ at the end of the file.
[lol] i just realized you wrote write not read, i'm losing my mind [embarrass].
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);

My project`s facebook page is “DreamLand Page”

This topic is closed to new replies.

Advertisement