3 Replies - 38043 Views - Last Post: 29 March 2006 - 04:53 AM Rate Topic: -----

#1 crammer008  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 09-February 06

How to read the whole TXT file into one string?

Posted 28 March 2006 - 08:51 PM

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
Is This A Good Question/Topic? 0
  • +

Replies To: How to read the whole TXT file into one string?

#2 Amadeus  Icon User is offline

  • g+ + -o drink whiskey.cpp
  • member icon

Reputation: 248
  • View blog
  • Posts: 13,507
  • Joined: 12-July 02

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:
#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.
Was This Post Helpful? 0
  • +
  • -

#3 crammer008  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 09-February 06

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
Was This Post Helpful? 0
  • +
  • -

#12 Amadeus  Icon User is offline

  • g+ + -o drink whiskey.cpp
  • member icon

Reputation: 248
  • View blog
  • Posts: 13,507
  • Joined: 12-July 02

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:
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.
Was This Post Helpful? 1

Page 1 of 1