This code is a part of a larger code that indexes files, and tokenizes the words in each file so that you can be able to search a certain word in the large amount of file you have. (like Google)
This function is supposed to search your files for a word that you want to find. But I don’t completely understand how it works!
Can someone please explain what this code does and how it does it?
In addition, I have several questions:
1) What exactly in “infile”?
2) What does the built-in function c_str() do?
3) Why does the variable “currentlineno” start at 1? Couldn’t the first line in a file start at 0?
4) What is the difference between ++x and x++?
5) What is the difference between the condition “currentlineno < lineNumber” and “currentlineno != lineNumber” ?
This is the code:
void DisplayResult(string fileName, int lineNumber)
{
ifstream infile(fileName.c_str(), ifstream::in);
char line[1000];
int currentlineno = 1;
while(currentlineno < lineNumber)
{
infile.getline(line, 1000);
++currentlineno;
}
infile.getline(line, 1000);
cout<<endl<<"\nResult from ("<<fileName<<" ), line #"<<lineNumber<<": "<<endl;
cout<<"\t"<<line;
infile.close();
}
This function display the line at the corresponding line number pass by parameter.
1/ Infile permits to open a file as in put streams : http://www.cplusplus.com/reference/fstream/ifstream/
2/ c_str() permits to pass to a string structure to a simple char* (a char array). It is the structure use in the language C, which explains why the method name is “c_str”. In C++, we usually use string more than char* cause it is really simpler.
3/ Why currentlineno start at 1 ? The function read the file content before the given line number. The, read one more time to display the wanted line.
4/ ++x is pre-incrementation, x++ is post-incrementation.
When you use ++x, x is incremented before to use it, otherwise, with x++, x is incremented after.
5/ Look at operators : http://www.cplusplus.com/doc/tutorial/operators/