Home > Software engineering >  Why does my C application consume too much system resources and not respond?
Why does my C application consume too much system resources and not respond?

Time:10-14

I want search a string in a text file. I use CodeBlocks as IDE.

Here are my codes:

string strLineToRead;

ifstream ifFile;
ifFile.open("FileToRead.txt");

while(strLineToRead.find("blabla") == string::npos)
{
     getline(ifFile, strLineToRead);
}

ifFile.close();

return 0;

CodePudding user response:

Your code contains a while loop, it would cause a lot of resources if your condition is not meet, in this case, it is strLineToRead.find("blabla") == string::npos, if that happens, you will enter into an infinite loop. Consider change your condition to this while(getline(ifFile, strLineToRead)) You can also consider open the file with open mode to reduce the resource.

CodePudding user response:

Below is a working example/demo that shows how to find a given string inside a text file:

main.cpp

#include <iostream>
#include <fstream>

int main()
{
    
    std::string line, stringtobeSearched = "blabla";

    std::ifstream inFile("input.txt");
    
    
    if(inFile)
    {
        while(getline(inFile, line, '\n'))        
        {
            //std::cout<<line<<std::endl;
            //if the line read does not contain the string searched for 
            if(line.find(stringtobeSearched) == std::string::npos)
            {
               ; //do something here
            }
            //if the line read contains the string searched for then print string  found
            else 
            {
                std::cout<<"string found "<<std::endl;
            }
            
            
        }
    }
    else 
    {
        std::cout<<"file could not be read"<<std::endl;
    }
    inFile.close();
    
    
   
    return 0;
}

input.txt

this is first line 
this is second blabla
third line is this 
blabla again found for second time 

The output of the above program is as follows(here):

string found 
string found
  • Related