Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Hamlet

reading a file

This topic is 5941 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a text file that contains lines of text. Each line ends with \n as normal. I have set up a function to count the number of lines in the file like this: do{ infile.getline( array, 256 ); counter++; }while( infile.peek() != EOF ); this gives me the number of lines. then i generate a random number based on counter. I want to go back to the file and pull out the line that corresponds with my random number. Can anyone put me on the right track as to how i can read that one line into an array to be stored and used by my driver? All help is appreciated. "... thats the rub...

Share this post


Link to post
Share on other sites
Advertisement
The 'brute force' approach:
call rewind( FILE *stream ); then reread a series of getlines, as many as necessary. You'll have your line.

The 'clever' approach:
Look up functions '_lseek' from io.h or 'fseek' from stdio.h and learn to use them for your purpose.

The 'Windows virtual memory' approach:
Learn to use the 'CreateFile', 'CreateFileMapping' and 'MapViewOfFile' triad of API functions. These will allow you to load up a file in memory (Virtual memory). And access it via a simple char* pointer, all at a higher speed than stdio.h functions allow.


Hope these help

=^.^=

[edited by - Spacecat on September 13, 2002 8:59:22 AM]

Share this post


Link to post
Share on other sites
The ''if the file is short enough'' approach:

Have an array of arrays to store the lines.

infile.getline( array[counter], 256 );

Then you already have the line you need... no rewinding required. It would be a bit easier and safer if you used std::string, although char arrays will suffice.

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost | Asking Questions | Organising code files | My stuff ]

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!