Solved

Going to a specific line in a txt file using ifstream

Posted on 2008-06-10
6
756 Views
Last Modified: 2013-12-14
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.
0
Comment
Question by:Snapples
6 Comments
 
LVL 53

Expert Comment

by:Infinity08
Comment Utility
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
 
LVL 30

Expert Comment

by:Zoppo
Comment Utility
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
 
LVL 2

Author Comment

by:Snapples
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 30

Accepted Solution

by:
Zoppo earned 500 total points
Comment Utility
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
 
LVL 11

Expert Comment

by:DeepuAbrahamK
Comment Utility
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
 
LVL 2

Author Comment

by:Snapples
Comment Utility
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

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now