T
tushar.saxena
Hi,
I'm trying to read a file using the istearm class (I cant use ifstream
since the input might be a file or it might be stdin).
istream *input;
// Add checks for file name here, else use input = &cin;
while (!input->eof())
{
char readbuffer[32];
input->getline(readbuffer,32);
// Do something here
}
My problem here is this :
If the line contains less than 32 characters, this works fine and
reads the whole line
However if the line contains more than 32 characters,
i. readbuffer[] contains the first 31 characters of the stream ----
iii. tellg() returns -1 ----> Not good
As a result of the tellg() function returning -1, subsequent
readline() calls are reading from position -1 from the file and as
such the readline() fails.
My Question :
How can I work around this ?
One possible solution I could think of is maintain a count of the
number of characters read and manually do a seekg() to that position
before every read. However this doesn't sound like a very elegant
solution and not very efficient at all.
Also, is it possible to read an entire line of a file into a string
(or maybe a stringstream?) ? Irresepctive of the the line in the input
stream.
Thx !
- Tushar
(Disclaimer : I know a buffer size of 32 is small and likely to be
inefficient due to the numerous file accesses, but I chose it for
debugging so I can see whats going wrong)
I'm trying to read a file using the istearm class (I cant use ifstream
since the input might be a file or it might be stdin).
istream *input;
// Add checks for file name here, else use input = &cin;
while (!input->eof())
{
char readbuffer[32];
input->getline(readbuffer,32);
// Do something here
}
My problem here is this :
If the line contains less than 32 characters, this works fine and
reads the whole line
However if the line contains more than 32 characters,
i. readbuffer[] contains the first 31 characters of the stream ----
ii. gcount() returns 31 ----> GoodGood
iii. tellg() returns -1 ----> Not good
As a result of the tellg() function returning -1, subsequent
readline() calls are reading from position -1 from the file and as
such the readline() fails.
My Question :
How can I work around this ?
One possible solution I could think of is maintain a count of the
number of characters read and manually do a seekg() to that position
before every read. However this doesn't sound like a very elegant
solution and not very efficient at all.
Also, is it possible to read an entire line of a file into a string
(or maybe a stringstream?) ? Irresepctive of the the line in the input
stream.
Thx !
- Tushar
(Disclaimer : I know a buffer size of 32 is small and likely to be
inefficient due to the numerous file accesses, but I chose it for
debugging so I can see whats going wrong)