Ahmed
Ahmed

Reputation: 3458

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_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

Answers (5)

nilay
nilay

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.

  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.

Upvotes: 0

user438921
user438921

Reputation: 1

Have a look on memory-mapped files in boost::iostreams.

Upvotes: 0

t0mm13b
t0mm13b

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

Gian
Gian

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

Chubsdad
Chubsdad

Reputation: 25497

The following are some of the available options:

istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );

Upvotes: 6

Related Questions