I want to search a particular word in a file & return a result as to whether that word exists in the file or not. I have created a function which does this. But while returning the program is crashing. Here is the code:
bool FindMyWord(const char *fileName)
{
ifstream myFile (fileName);
if(!myFile)
return false;
string wordSearch = "MyWord";
string endSearch = "LastWord";
bool result;
while(1)
{
char read[20];
myFile.getline(read, 1000, '
');
string line(read, read+20);
if(line.find(wordSearch) != string::npos)
{
result = true;
break; //comes here after looping about 10 times
}
if(line.find(endSearch) != string::npos)
{
result = false;
break;
}
}
myFile.close();
return result;
} // <- crash when F10 is pressed after this
In VS2010 while debugging I find that the crash is happening after executing "return result;
" in second last line of the function i.e. when the yellow cursor is for the last closing bracket of function.
I am getting a message
A buffer overrun has occurred in myApp.exe which has corrupted the program's internal
state. Press Break to debug the program or Continue to terminate the program.
What is this error? I am calling the function like this :
bool result = FindMyWord("myFileName.stp");
UPDATE: Each line has varying no of characters & they are > 20. I want to read the 1st 20 characters & if the word does not exist in those characters then I want to jump to the next line. Initially I had used myFile.getline(read, 20, '
');
But after the 1st loop every subsequent looping resulted in NULL being passed to read. So I made it to read 1000 because before reading 1000 chars it would find '
' & go to next line.
A better mechanism of achieving the same would be very helpful.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…