I'm implementing a "grep"-type thing for windows (partly for the experience, I know it's been done). Right now, I have it store an entire line of a file into a char *-style string and see if that matches the appropriate regular expression:
(Don't worry about the regex-specific functions, I know they are working.) My question is that this seems wasteful, and I'm looking for an alternative solution. I've defined it to allocate 1024 characters when most lines are less than 80. But it seems like a bad idea to use any finite value. Is there a way to determine the length of a line, or just keep reading from the file until you get to a '\n' (without worrying about the number of characters)?Code:const char charsPerLine = 1024; // theFile is defined as an ifstream object for( int lineNum = 1; !theFile.eof(); lineNum++ ) { char * theLine = new char[ charsPerLine + 1 ]; theFile.getline( theLine, charsPerLine ); match_results results; if( thePat.match( theLine, results ) ) cout << lineNum << ": " << theLine << "\n"; delete [] theLine; }
Alternatively, is there a way to read the whole file in at once ("slurp" it, in perl terms)? I guess I could use ifstream.read() but I would have to know how many bytes to read...TIA for advice.