Dear all,
How to read the whole TXT file into one string?
The TXT file is a multi-line file and its size is not known.
Looking forward to your guidance!
Thanks a lot
Crammer008
How to read the whole TXT file into one string?
Page 1 of 13 Replies - 30641 Views - Last Post: 29 March 2006 - 04:53 AM
Replies To: How to read the whole TXT file into one string?
#2
Re: How to read the whole TXT file into one string?
Posted 28 March 2006 - 10:22 PM
How can the size not be known? Is it an open text file that is being written to while it is being read from. Here is a link to some common filke i/o manipulation:
http://www.cplusplus...rial/files.html
As discussed on that page, you can obtain the file size like so:
That determined size can then be used to read the file to a single string object.
http://www.cplusplus...rial/files.html
As discussed on that page, you can obtain the file size like so:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
long begin,end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
That determined size can then be used to read the file to a single string object.
#3
Re: How to read the whole TXT file into one string?
Posted 29 March 2006 - 12:25 AM
Thank you very much!
You code helps to get the size of the file:)
My question is how to read the whole file into a string.
Every time, the file will be produced with different size. This is the reason I said the size is unknown.
Thank you:)
Crammer008
You code helps to get the size of the file:)
My question is how to read the whole file into a string.
Every time, the file will be produced with different size. This is the reason I said the size is unknown.
Thank you:)
Crammer008
#12
Re: How to read the whole TXT file into one string?
Posted 29 March 2006 - 04:53 AM
You would check the file size everytime you need to read it. As for reading it to the string, you can do it several ways:
This will read the file line by line and append it to a string...keep in mind this method will take out the newlines, so if you want them, you'll have to put them in yourself...
There are other methods as well.
string str,strTotal;
ifstream in;
in.open("myfile.txt");
getline(in,str);
while ( in ) {
strTotal += str;
getline(in,str);
}
This will read the file line by line and append it to a string...keep in mind this method will take out the newlines, so if you want them, you'll have to put them in yourself...
There are other methods as well.
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote



|