tags:

views:

84

answers:

4

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 .

+6  A: 

The following are some of the available options:

istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );
Chubsdad
still the same problem .
Ahmed
@Ahmed: what is the issue?
Chubsdad
is and str will have a fixed size and I want a solution that reallocates according to the size of input .
Ahmed
@Ahmed, these functions would do that unil string::max_size() elements are read.
Chubsdad
@Ahmed: If you use std::getline() and std::string then the only practical limit is available memory. Are you having lines bigger than that? :)
wilx
It worked fine . I was missing the difference between this getline and the other one but now I understood.
Ahmed
+1  A: 

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.

Gian
A: 

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

tommieb75
Okay, I suppose you cam do this. But sounds like massive overkill given that a solution is in the standard library.
Billy ONeal
A: 

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

Memory mapping doesn't help you here. You'd still need to know the size of the file to map.
Billy ONeal