Solved

Going to a specific line in a txt file using ifstream

Posted on 2008-06-10
6
765 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 53

Expert Comment

by:Infinity08
ID: 21749667
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 31

Expert Comment

by:Zoppo
ID: 21749686
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
ID: 21749774
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 31

Accepted Solution

by:
Zoppo earned 500 total points
ID: 21749799
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
ID: 21750095
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
ID: 21751256
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Error C2678: binary '!=': no operator found... 4 72
Syntax Error 2 112
Autosar OS Multicore Share Resources confusion ? 2 195
boost::uuid crashes 17 61
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Programmer's Notepad is, one of the best free text editing tools available, simply because the developers appear to have second-guessed every weird problem or issue a programmer is likely to run into. One of these problems is selecting and deleti…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

734 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