parse an unknown size string
I am trying to read an unknown size string from a text file and I used this code :
ifstream inp_开发者_JS百科file;
char line[1000] ;
inp_file.getline(line, 1000);
but I don't like it because it has a limit (even I know it's very hard to exceed this limit)but I want to implement a better code which reallocates according to the size of the coming string .
The following are some of the available options:
istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );
One of the usual idioms for reading unknown-size inputs is to read a chunk of known size inside a loop, check for the presence of more input (i.e. verify that you are not at the end of the line/file/region of interest), and extend the size of your buffer. While the getline primitives may be appropriate for you, this is a very general pattern for many tasks in languages where allocation of storage is left up to the programmer.
Maybe you could look at using re2c which is a flexible scanner for parsing the input stream? In that way you can pull in any sized input line without having to know in advance... for example using a regex notation
^.+$
once captured by re2c you can then determine how much memory to allocate...
Have a look on memory-mapped files in boost::iostreams.
Maybe it's too late to answer now, but just for documentation purposes, another way to read an unknown sized line would be to use a wrapper function. In this function, you use fgets()
using a local buffer.
- Set last character in the buffer to
'\0'
- Call
fgets()
- Check the last character and see if it's still
'\0'
- If it's not
'\0'
and it's not'\n'
, implies not finished reading a line yet. Allocate a new buffer and copy the data into this new buffer and go back to step (1) above. - If there is already an allocated buffer, call
realloc()
to make it bigger. Otherwise, you are done. Return the data in an allocated buffer.
- If it's not
This was a tip given in my algorithms lecture.
精彩评论