James MV
James MV

Reputation: 8717

Read only given line from text file?

Is there a way in C++ to grab a random number up to a given size then read that line from a text file? Without having to step through all the lines? I've got this which just prints out line by line:

#include <cstdio>
#include<iostream>
#include<fstream>

using namespace std;
int main(int argc, char* argv[]){
    ifstream myReadFile;
    myReadFile.open("words.txt");
    char output[100];
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {
            printf("\n");
            myReadFile >> output;
            cout<<output;
        }
    }
    myReadFile.close();
    return 0;
}

Upvotes: 1

Views: 591

Answers (5)

Michael Kristofik
Michael Kristofik

Reputation: 35178

There's seekg that you can use to advance to a particular address within the file. But unless you can guarantee something about how long each line is, you can't be sure that your random offset actually begins on a new line.

By the way, the given code in the question actually reads one word at a time, not one line at a time. To read an entire line at once, use std::getline.

Upvotes: 1

Paul Nikonowicz
Paul Nikonowicz

Reputation: 3903

In order to read a line in a file you have to understand that line is delimited by a '\n' character. therefore, you will have to read the entire file no matter what.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

In general, no: lines are delimited with a special character, your program would need to read all characters, and count the line breaks in order to do what you need.

In special cases when your lines are all of the same length (which happens more often in programming competitions than in practice) you could reposition the file read pointer to a specific place, and read your line from there.

P.S. The only place where I saw it in practice was UUENCODEd files.

Upvotes: 4

Mark Ransom
Mark Ransom

Reputation: 308111

There's no way to do it unless you know the size of each line through some other means. Then you could add up the sizes of the lines you want to skip and do a seekg to skip to the start of the line.

Upvotes: 9

m0skit0
m0skit0

Reputation: 25863

Without having to step through all the lines?

AFAIK, no.

Upvotes: 2

Related Questions