File reading/writting and STL strings
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?
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');
fin.write(&*str.begin(), str.size());
You can use std::getline to read a string
std::getline(fin, str, '\n');
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.
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.
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);
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement