Computing.Net > Forums > Programming > How to read whole file? (C++)

How to read whole file? (C++)

Reply to Message Icon

Original Message
Name: Leo the 28C (by Sulfurik)
Date: September 4, 2005 at 16:54:42 Pacific
Subject: How to read whole file? (C++)
OS: Windows XP Home SP2
CPU/Ram: 2.8 GHz/448 MB
Comment:

Hello everyone! :D
Does anybody know how I could read a WHOLE text file in C++? I mean like, reading all of the lines of a file (separated by \n) into a single string... In C# you could do it with StreamReader.ReadToEnd(), but I don't know how to do it in C++... anybody know? Thanks! ;)

http://www.xthost.info/sulfurik/
http://tsfc.ath.cx
ftp://tsfc.ath.cx
hotline://tsfc.ath.cx

Ruffle Mayo says ROFLMAO! :D


Report Offensive Message For Removal


Response Number 1
Name: Stephen Hall
Date: September 4, 2005 at 18:54:13 Pacific
Reply: (edit)

Sulfurik,

Just use some stream input and output. It's not quite the same as C#, but it's the same idea. Here's a layout

1) Open a file with fopen.
2) Find the size of the file using fseek and ftell.
3) Use fread to read the file into a properly allocated buffer.

That's about all there is to it.

Stephen

"Live long and PROGRAM......or at least do _something_ with all that time...!"


Report Offensive Follow Up For Removal

Response Number 2
Name: Leo the 28C (by Sulfurik)
Date: September 4, 2005 at 19:01:46 Pacific
Reply: (edit)

Aaaand how would I do that? Sorry, this is the fisrt day I ever got to C++... :-P For 1, I can do that, for 2, I can probably figure it out, but how do I do 3? Thanks! ;-)

http://www.xthost.info/sulfurik/
http://tsfc.ath.cx
ftp://tsfc.ath.cx
hotline://tsfc.ath.cx

Ruffle Mayo says ROFLMAO! :D


Report Offensive Follow Up For Removal

Response Number 3
Name: Leo the 28C (by Sulfurik)
Date: September 4, 2005 at 19:05:21 Pacific
Reply: (edit)

Oh, and... I've been trying to do it with both fopen and ifstream, isn't ifstream easier? Thanks! ;)

http://www.xthost.info/sulfurik/
http://tsfc.ath.cx
ftp://tsfc.ath.cx
hotline://tsfc.ath.cx

Ruffle Mayo says ROFLMAO! :D


Report Offensive Follow Up For Removal

Response Number 4
Name: Stephen Hall
Date: September 4, 2005 at 19:21:57 Pacific
Reply: (edit)

Sulfurik,

I guess ifstream would be "easier", but in my estimation, there really isn't anything "easier" than what you are most comfortable with. Sure there are people who would disagree with me, and Microsoft is phasing out the good old Standard C Library, but it's what I learned when I was a teenager and I just haven't changed yet. Here's how you'd do it using the fopen type functions.

FILE *fp;
long len;
char *buf;
fp=fopen("thefileyouwanttoread.txt","rb");
fseek(fp,0,SEEK_END); //go to end
len=ftell(fp); //get position at end (length)
fseek(fp,0,SEEK_SET); //go to beg.
buf=(char *)malloc(len); //malloc buffer
fread(buf,len,1,fp); //read into buffer
fclose(fp);

I didn't put any exception handling in there, which there should be. Just check the return codes on those functions and make sure they don't return an error (NULL or 0 in all cases). Anyways, again, take it for what it's worth. It would _work_ even though it may not be "easiest", but hey, can you beat 10 lines of code, maybe 15 with error checking? Maybe so, but who cares anyway?!
Hey, best of luck on whatever you're doing. Let me know if this works for ya!


Stephen

"Live long and PROGRAM......or at least do _something_ with all that time...!"


Report Offensive Follow Up For Removal

Response Number 5
Name: Leo the 28C (by Sulfurik)
Date: September 4, 2005 at 20:38:09 Pacific
Reply: (edit)

Yep, worked! :-D Thanks! ;-) But now, I have another question... How do I do to find a substring inside of a string? (Actually a char *) On a website, they say that "strstr()" doesn't include terminating null-characters... But I need it to find stuff like "\n" and "\r" and such... Is there a function for this? Thanks! ;-)

http://www.xthost.info/sulfurik/
http://tsfc.ath.cx
ftp://tsfc.ath.cx
hotline://tsfc.ath.cx

Ruffle Mayo says ROFLMAO! :D


Report Offensive Follow Up For Removal


Response Number 6
Name: Stephen Hall
Date: September 5, 2005 at 18:01:39 Pacific
Reply: (edit)

Sulfurik,

Great to hear that that little piece of code helped you out. I think it'd be really cool though if you went on and developed the same thing in ifstream. I would if I wasn't so busy developing a site right now. Remember that having many different ways to do something in programming is common and it's good to have a couple different tricks "up your sleve".
Anyways, why won't strstr work for you? '\n' and '\r' are not terminating NULL's ('\0'), so it will find things like that just fine. For example, say you wanted to change every '\n\r' combination (I think that's the order they come in, but I always have to look it up to be sure. One's 10 and one's 13, and I _think_ it's 13 10, but I don't know) into two spaces (why, I don't know....), you could do something like this.

char *str;
str=filebuffer;
while((str=strstr(str,'\n\r')))
{
str[0]=' ';
str[1]=' ';
str+=2;
}

Let me explain. Make a temporary variable for storing the string (I like str, but use what you like) -- definitely don't use the filebuffer or you'll end up all trashed at the end. Now use strstr to find the next occurence of '\n\r'. strstr returns a pointer value (not NULL) if it finds a string and NULL if it doesn't. Remember that in C/C++, NULL evaluates to FALSE in a conditional statement (if's, for's, while's, etc.). Since strstr's return is put in str, the while will evaluate the truth of the condition on str's value. If str is not NULL, the loop will execute, if it is NULL (i.e. we've run out of \n\r combinations), the loop will terminate.
Now, inside the loop we change the first two characters str is pointing to to spaces. The reason for this is that they were '\n' and '\r' (strstr returns the address at which the searched for string occurs). The last line moves us past the \n\r pair. This is not critical in this situation since the \n\r pair was replaced by ' ', but if we hadn't replaced them (i.e. we were just counting the number of lines in the file), this would be extremely critical. Otherwise you'd end up in one of those dreadful infinity loops that can lock up a computer in the wrong situation (a high priority thread). Anyways, after the alteration of the string and the unnecessary skipping of the altered characters, strstr is called again, but this time the search resumes from where we left off before. The loop continues through to the end of the string.
In terms of security, the loop is fine since the last '\n\r' pair will be followed by a '\0' (NULL) character. Once we increment past the last \n\r pair, str will point to a '\0' character which, when passed to strstr, will act as a zero lenght string. strstr will dump out early and return a NULL value which will get us out of the loop.

Sorry this is so long, but I like talking about this stuff! I'm really sorry if I'm taking everything to a simplistic level, but that's how I think through everything so as not to end up in problems. To make a long story short, strstr will work fine for you.

Stephen

"Live long and PROGRAM......or at least do _something_ with all that time...!"


Report Offensive Follow Up For Removal

Response Number 7
Name: Cache
Date: September 6, 2005 at 16:29:04 Pacific
Reply: (edit)

I guess ifstream would be "easier", but in my estimation, there really isn't anything "easier" than what you are most comfortable with. Sure there are people who would disagree with me, and Microsoft is phasing out the good old Standard C Library, but it's what I learned when I was a teenager and I just haven't changed yet. Here's how you'd do it using the fopen type functions.

FILE *fp;
long len;
char *buf;
fp=fopen("thefileyouwanttoread.txt","rb");
fseek(fp,0,SEEK_END); //go to end
len=ftell(fp); //get position at end (length)
fseek(fp,0,SEEK_SET); //go to beg.
buf=(char *)malloc(len); //malloc buffer
fread(buf,len,1,fp); //read into buffer
fclose(fp);

------------

Assuming im reading this correctly, this would be my preferred way to solve the problem using string, vector, and ifstream.

vector<string> text;
string line;
ifstream textstream ("whatever.txt");
while (getline(textstream, line)) {
text.push_back(line + "\n");
}
textstream.close();
string alltext;
for (int i=0; i < alltext.size(); i++)
alltext += text[i];


Report Offensive Follow Up For Removal

Response Number 8
Name: Cache
Date: September 6, 2005 at 16:37:15 Pacific
Reply: (edit)

I should have aslo sead: the result of the above code is to place everything from whatever.txt into the string alltext.


Report Offensive Follow Up For Removal

Response Number 9
Name: Cache
Date: September 6, 2005 at 16:55:17 Pacific
Reply: (edit)

Is there no way to edit posts on this forum? lol.

I made a mistake on this line:
for (int i=0; i < alltext.size(); i++)

It should read:
for (int i=0; i < text.size(); i++)

Sorry


Report Offensive Follow Up For Removal

Response Number 10
Name: Leo the 28C (by Sulfurik)
Date: September 7, 2005 at 19:19:52 Pacific
Reply: (edit)

Yep, fixed! Thanks you two! :D

http://www.xthost.info/sulfurik/
http://tsfc.ath.cx
ftp://tsfc.ath.cx
hotline://tsfc.ath.cx

Ruffle Mayo says ROFLMAO! :D


Report Offensive Follow Up For Removal






Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: How to read whole file? (C++)

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes In 5 Days.
Discuss in The Lounge