Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from a specific spot in a file C++

I have a program in C++ that needs to return a line that a specific word appears in. For instance, if my file looks like this:

the cow jumped over
the moon with the
green cheese in his mouth

and I need to print the line that has "with". All the program gets is the offset from the beginning of the file (in this case 24, since "with" is 24 characters from the beginning of the file).

How do I print the whole line "the moon with the", with just the offset?

Thanks a lot!

like image 669
Meir Avatar asked Jun 10 '12 12:06

Meir


People also ask

How to read from middle of file in C?

pos /= 2; printf("The middle of the file is at %d bytes from the start. \n", pos); /* Position stream at the middle.

How to open a file and read in C?

Steps To Read A File:Open a file using the function fopen() and store the reference of the file in a FILE pointer. Read contents of the file using any of these functions fgetc(), fgets(), fscanf(), or fread(). File close the file using the function fclose().

Can we read and write a file at the same time in C?

From Pelles C help file: When a file is opened with update mode ('+' as the second or third character in the mode argument), both input and output may be performed on the associated stream.


1 Answers

You can do this by reading each line individually and recording the file position before and after the read. Then it's just a simple check to see if the offset of the word falls within the bounds of that line.

#include <iostream>
#include <fstream>
#include <string>

std::string LineFromOffset(
    const std::string &filename,
    std::istream::pos_type targetIndex)
{
    std::ifstream input(filename);

    //  Save the start position of the first line. Should be zero of course.
    std::istream::pos_type  lineStartIndex = input.tellg();

    while(false == input.eof())
    {
        std::string   line;

        std::getline(input, line);

        //  Get the end position of the line
        std::istream::pos_type  lineEndIndex = input.tellg();

        //  If the index of the word we're looking for in the bounds of the
        //  line, return it
        if(targetIndex >= lineStartIndex && targetIndex < lineEndIndex)
        {
            return line;
        }

        // The end of this line is the start of the next one. Set it
        lineStartIndex = lineEndIndex;
    }

    //  Need a better way to indicate failure
    return "";
}

void PrintLineTest()
{
    std::string str = LineFromOffset("test.txt", 24);

    std::cout << str;
}
like image 192
Captain Obvlious Avatar answered Oct 11 '22 23:10

Captain Obvlious