Going to a specific line in a txt file using ifstream

Hello experts.
I'm currently using ifstream to go through a text file line per line, when encountering, for example, the character $ at the beginning of the line, it saves that line's number in an array.
Now I'd need to be able, without closing that ifstream if possible, to go to that line without going through all the previous ones and start using getline from that position.
How could I best do that?

Thanks in advance.
LVL 2
SnapplesAsked:
Who is Participating?
 
ZoppoConnect With a Mentor Commented:
Hi,

yes, this should work if you read the position with tellg() before reading the line - so I guess you need to do the tellg() before you parse the line whether it contains the '$'.

BTW, you should use 'ifstream::pos_type' instead of 'int' because it might be a file is longer than 4GB ...

ZOPPO
0
 
Infinity08Commented:
Unless the lengths of all lines are known (ie. probably the same), this is not easily possible. You will have to actually read (n-1) lines from the file, and the next line is the line you want.


If the file is not too big, you might consider reading the entire file into an array of strings (one string for each line). That way you can use array indexing to get to the line you need.
0
 
ZoppoCommented:
Hi Snapples,

you could store in addition to the linenumber the read-position in the file (retrieve this with istream::tellg()) and use this to later position the ifstream's read-position istream::with seekg(...)

ZOPPO
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
SnapplesAuthor Commented:
I don't think storing the entire file in an array would be a good idea in my case because the size of the array depends on the user. The file that has to be read is a file that my program wrote earlier, 1 line per second. So the user could abuse it and leave it open for 4 hours for example.

And except for some lines, every line is the same lenght. I'm writing sort of a log file, that writes what the user is doing. For example:
[Start of File]
400|140|0|0000|0077|0000|0077|000|1|0|0|0|0|000|000|000|000|000|000|
352|140|0|0154|0231|0308|0385|000|0|0|0|0|1|398|140|373|137|000|000|

Now I want to read those line per line, but only starting from a certain point.

Zoppo, so would this work?

int pos = ReadFile.tellg();
ReadFile.seekg(pos,ios::beg);

seekg goes to the position of pos starting to count from the beginning is that right?
0
 
Deepu AbrahamR & D Engineering ManagerCommented:
1.store the pos after each end of line (\n)
2.check for $
3.if $ sore that pos in an array (int Posarray[0]=10,Posarray[1]=20...etc)
4.continue till end if file.
5.using this

  ifstream file (filename, ios::in|ios::binary);  
  file.seekg (posarray[0], ios::begin); //you can go that 10th position.
  file.seekg (posarray[0], ios::begin); //you can go that 20th position.
Best Regards,
DeepuAbrahamK
0
 
SnapplesAuthor Commented:
Hmmm it doesn't seem to work.
This is what I have, see code snippet.

Instead of returning back to the StartPos, as result I keep getting Messageboxes that say 0, so an empty line. Even if I change m_StartPos by 0, it still doesn't go back to the starting point.


	if (!m_ReadFile) 
        {
            MessageBox("not exist");
            return false;
        }
        else
        {
            while (!m_ReadFile.eof())
            {
                getline(m_ReadFile, Line);
                OutputDebugString(Line.c_str());    
                OutputDebugString("\n");
                if (Line.substr(0,6) == "[ERROR")
                {
                    MessageBox("The file you have selected was corrupted or has been altered. You will now return to the main screen.");
                    m_Error = true;
                    break;
                }
                else if (Line.substr(0,15) == "[Start of File]")
                {
                    m_StartPos = m_ReadFile.tellg();
                }
            }
 
 
// The above works
 
bool CPU::ReadLine()
{
    if (m_Check)
    {
        string Line;
        m_ReadFile.seekg(m_StartPos,ios::beg);
        getline(m_ReadFile,Line);
 
        OutputDebugString(Line.c_str());
        OutputDebugString("\n");
 
        if (Line.length() != 68)
        {
            MessageBox(String("") + Line.length());
            return false;
        }
        else
        {
            if (Line == "[End of File]")
            {
                m_Check = false;
            }
            else if (Line == "[End of Attack]")
            {
            
            }
            else
            {
                int temp = 0;
 
                stringstream StrBuffer;
                StrBuffer.clear();
                StrBuffer.str("");
 
                StrBuffer << Line.substr(0,3);
                StrBuffer >> temp;
 
                MessageBox(String("") + temp);
                return true;
 
 
            }
        }
 
    }
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.