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!
pos /= 2; printf("The middle of the file is at %d bytes from the start. \n", pos); /* Position stream at the middle.
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().
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With