Archived

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

Ekim_Gram

How can you read a specific line from a file (C++)

Recommended Posts

Ekim_Gram    418
Is there a way of using I/O streams (fstream, ostream, ect.) to read a certain line from a text file? Like, say I use the following random number generating code:
int x;
srand(GetTickCount());
x = rand()%10;
If x = 9 for instance, since the random numbers start at 0 and I'm guessing the lines in a .txt file would start at 0 as well, can I read line 10 and print it to the screen or save it to an array? EDIT: sorry, I meant to put this in the General Programming forum.
There's no town drunk here, we all take turns. Velocity Gaming Force [edited by - Ekim_Gram on August 13, 2003 12:02:37 AM]

Share this post


Link to post
Share on other sites
_SKOTTIE_    122
well in a binary file (such as a text file) there is no way for random access, you would have to look into a differetn file type, however, with x being a random number, you certain could do something like this:


#include <fstream.h>

char* GetRandomLineFromFile(char* filename, int fileline)
{
char* requested_line = new char[256];

ifstream in_file;
in_file.open(filename);

//this is our garbage variable to eat up lines

char* garbage = new char[256];

for(int x = 1; x < fileline; ++x)
{
in_file >> garbage;
}

//now get the line we want

in_file >> requested_line;

delete garbage;

return requested_line;
}

Share this post


Link to post
Share on other sites
ToohrVyk    1595

char * Data;
vector<char*> LineStart;
//

//

void Read( char * Filename ) {
//

//

//

//first, read in all the file

fstream in( filename, ios::in );
in.seekg( 0, ios::end );
long FileSize = in.tellg( );
Data = (char*)malloc( FileSize );
in.seekg( 0 );
in.read( Data, FileSize );
//

//

//

//Now, we're going to create a vector,

//and store the starting index of each

//line

char * Start = Data;
LineStart.push_back( Start );
//

//

//

while( (*Start != '\0') ) {
if(*Start == '\n' ) {
*Start = '\0';
LineStart.push_back( ++Start );
}
else {
++Start;
}
}
}
//

//

//

//finally, the read function :

char * RequestedLine( int X ) {

return( LineStart[X] );
}



ToohrVyk



[edited by - ToohrVyk on August 14, 2003 2:28:19 AM]

Share this post


Link to post
Share on other sites
Beer Hunter    712

std::string getLineFromFile(const char* filename, int lineNum)
{
std::string result;
std::ifstream f(filename);
for (int i = 0; i <= lineNum; ++i) std::getline(f, result);
return result;
}


[edited by - Beer Hunter on August 14, 2003 2:44:14 AM]

Share this post


Link to post
Share on other sites