Skip to main content
GameDev.net gamedev.net
🔒 Locked

Reading specific line

Started by NukeCorr Sep 24, 2007 at 1:58 AM 2 replies 1k views
Original Post
NukeCorr
NukeCorr
Hello. I'm using C++. What is the best way to read a specific line from a .txt file? For example: ReadLine(7); That would get the string on line 7 in the .txt file. But how to make it read some specific one?
What the h*ll are you?
dopelganger
dopelganger
#include <iostream>#include <fstream>using namespace std;bool ReadLine( ifstream* file, char* storage, int storageLen, int lineNumber ){    // init    int actualLine = -1;    // set get seek to 0    input->seekg( 0, ios_base::beg );    // searching loop    while( actualLine++ != lineNumber && !file->eof() )    {        file->getline( storage, storageLen );    }    // result    if ( actualLine-1 == lineNumber )        return true;    // def result    return false;}void main( void ){   // line buffer   char line[ 512 ];   // open input file as text   ifstream* input = new ifstream( "dictionary.txt", ios::in );      cout << "Line number ";   if ( ReadLine( input, (char*)line, 512, 7 ) )      cout << 7 << ": " << line << endl;   else      cout << 7 << ": not found" << endl;}
Evil Steve
Evil Steve
Remember that files are just a one-dimensional array of bytes, there's no concept of lines. What you see in a text editor appear as lines because the editor splits the data on newline characters. You'd have to go through and count the number of newlines (As dopelganger showed), and then read until the next newline.
NukeCorr
NukeCorr
Thanks, I'm sure this'll help me out
What the h*ll are you?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.