How to get position of a search in the text file?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Alex T
    New Member
    • Oct 2010
    • 29

    How to get position of a search in the text file?

    Hello, I have a bit of a problem here: I am trying to make the search find the positions of a string in the text file.

    The .txt file is very large and the string comes up multiple times, so I need a way to delete part of the txt file up to the point I see the first occurence of the word

    Here is my code:

    Code:
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    #include <string>
    #include "sourcetxt.h"
    
    using namespace std;
    
    const string prntpath = "C:\\data.txt";
    
    class txtfiles
    {
    private:
    	CURLcode crl;
    	int offset;
    	string url;
    	string frgdate;
    	string search;
    	ifstream infile;
    public:
    	txtfiles() //constructor for url
    	{
    		cout << "Enter the URL:";
    		cin >> url;
    
    		crl = copy(url, prntpath);
    	};
    
    	const int& organize()
    	{
    		infile.open(prntpath);
    
    		if (infile.fail())
    		{
    			cout << "Error: Could Not Open Input File!";
    			return 1;
    		}
    
    		cout << "Successfully Opened Input File." << endl;
    		
    		search = ", 200";
    		while (infile.good())
    		{
    			while (!infile.eof())
    			{
    				getline(infile, frgdate);
    				if ((offset = frgdate.find(search, 0)) != string::npos) 
    				{
    					cout << "found '" << search << "' @ offset " << offset << endl;
    					return 0;
    				}
    			}
    		}
    	};
    };
    I currently need help with 2 things:
    1. Getting position of the string in the text file
    2. Erasing the previous part of the text file

    If you have experience, please help me.
  • rstiltskin
    New Member
    • Feb 2010
    • 14

    #2
    You can use infile.tellg() to find out the position of the beginning of each line -- use it as the last statement in the loop so you'll know the position before each call to getline. Then adjust that value by the position of your search string in the line.



    By the way, your code doesn't seem to allow for the possibility that the search string might overlap the end of a line. If that's a possibility, you can save the last few (search string length - 1) characters of each line to search with the next line.

    Also, instead of
    Code:
           while (infile.good())
           {
                while (!infile.eof())
                {
                    getline(infile, frgdate);
                    // ...
    why not
    Code:
           while (getline(infile, frgdate)
           {
                     // ...

    Comment

    Working...