Reputation: 3458
I am trying to read an unknown size string from a text file and I used this code :
ifstream inp_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 .
Upvotes: 0
Views: 1595
Reputation: 185
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.
'\0'
fgets()
'\0'
'\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.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.
Upvotes: 0
Reputation: 34592
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...
Upvotes: 0
Reputation: 13945
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.
Upvotes: 2