开发者

parse an unknown size string

开发者 https://www.devze.com 2023-01-14 02:49 出处:网络
I am trying to read an unknown size string from a text file and I used this code : ifstream inp_开发者_JS百科file;

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.

  1. Set last character in the buffer to '\0'
  2. Call fgets()
  3. 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.

This was a tip given in my algorithms lecture.

0

精彩评论

暂无评论...
验证码 换一张
取 消