Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Going to a specific line in a txt file using ifstream

Posted on 2008-06-10
6
Medium Priority
?
773 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 31

Accepted Solution

by:
Zoppo earned 2000 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:Deepu Abraham
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

Technology Partners: 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

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

618 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