473,699 Members | 2,628 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading a file using istearm

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(readbu ffer,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 ----
Good
ii. gcount() returns 31 ----Good
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)
Dec 13 '07 #1
4 1929
On Dec 13, 11:14 am, tushar.sax...@g mail.com wrote:
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(readbu ffer,32);
// Do something here

}
std::string buf("");
while(getline(i nput,buf))
{
//do proessing, if any
}

this getline is provided by string. do not forget to include <string>.
hope this works.
>
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 ----Good

ii. gcount() returns 31 ----Good
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)
Thanks,
Balaji.

Dec 13 '07 #2
Works like a charm. Thx !

On Dec 12, 10:26 pm, kasthurirangan. bal...@gmail.co m wrote:
On Dec 13, 11:14 am, tushar.sax...@g mail.com wrote:
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(readbu ffer,32);
// Do something here
}

std::string buf("");
while(getline(i nput,buf))
{
//do proessing, if any

}

this getline is provided by string. do not forget to include <string>.
hope this works.


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 ----Good
ii. gcount() returns 31 ----Good
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)

Thanks,
Balaji.
Dec 13 '07 #3
In message
<23************ *************** *******@b40g200 0prf.googlegrou ps.com>,
ka************* ******@gmail.co m writes
>On Dec 13, 11:14 am, tushar.sax...@g mail.com wrote:
>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())
It's also worth pointing out that this is almost never the right thing
to do. eof() doesn't become true until *after* you have tried (and
failed) to read beyond the end of the file.
>{
char readbuffer[32];
input->getline(readbu ffer,32);
// Do something here

}
This is the correct way: note that the test for failure takes place
*after* the call of getline().
>std::string buf("");
while(getline( input,buf))
{
//do proessing, if any
}

this getline is provided by string. do not forget to include <string>.
hope this works.
[snip]

--
Richard Herring
Dec 13 '07 #4
On Dec 13, 11:17 am, Richard Herring <ju**@[127.0.0.1]wrote:
In message
<23801a42-f402-4b4d-a659-a44b36dfd...@b4 0g2000prf.googl egroups.com>,
kasthurirangan. bal...@gmail.co m writes
On Dec 13, 11:14 am, tushar.sax...@g mail.com wrote:
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())
It's also worth pointing out that this is almost never the
right thing to do. eof() doesn't become true until *after* you
have tried (and failed) to read beyond the end of the file.
Actually, whether it becomes true or not depends. You can't
count on it one way or the other.
{
char readbuffer[32];
input->getline(readbu ffer,32);
// Do something here
}
This is the correct way: note that the test for failure takes
place *after* the call of getline().
And it doesn't involve calling eof().
std::string buf("");
while(getline(i nput,buf))
{
//do proessing, if any
}
this getline is provided by string. do not forget to include
<string>. hope this works.
Note too that in his original code: getline() sets failbit if it
cannot read a line, because the buffer is too small. (This
shouldn't be a problem with the version using std::string,
although in extreme cases, you may get a bad_alloc exception
from it.) And error status is sticky; the error remains (and
all further operations are no-ops) until it is explicitly
cleared.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Dec 13 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
7047
by: fabrice | last post by:
Hello, I've got trouble reading a text file (event viewer dump) by using the getline() function... After 200 - 300 lines that are read correctly, it suddenly stops reading the rest of the file... Thank you to all of you who can help me with this one...
19
10323
by: Lionel B | last post by:
Greetings, I need to read (unformatted text) from stdin up to EOF into a char buffer; of course I cannot allocate my buffer until I know how much text is available, and I do not know how much text is available until I have read it... which seems to imply that multiple reads of the input stream will be inevitable. Now I can correctly find the number of characters available by: |
1
4383
by: Michael Palmer | last post by:
I'm reading xml from SQL Server 2K with VB.net using an XSD schema file and SQLXML 3.0. I have the below code working fine, but I'd like to change the code from reading the schema file from a directory to reading the schema as an embedded resource. Here's my current code, what would I need to change?? Dim strm As Stream Dim strmReader As StreamReader Dim cmd As New SqlXmlCommand("MyConnectionString") Dim xmlDoc As New XmlDocument
4
9836
by: Oliver Knoll | last post by:
According to my ANSI book, tmpfile() creates a file with wb+ mode (that is just writing, right?). How would one reopen it for reading? I got the following (which works): FILE *tmpFile = tmpfile(); /* write into tmpFile */ ...
6
3790
by: KevinD | last post by:
assumption: I am new to C and old to COBOL I have been reading a lot (self teaching) but something is not sinking in with respect to reading a simple file - one record at a time. Using C, I am trying to read a flatfile. In COBOL, my simple file layout and READ statement would look like below. Question: what is the standard, simple coding convention for reading in a flatfile - one record at a time?? SCANF does not work because of...
7
6059
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should populate a series of structures of specified variable composition. I have the structures created OK, but actually reading the files is giving me an error. Can I ask a simple question to start with: I'm trying to read the file using the...
6
5267
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
5
14985
blazedaces
by: blazedaces | last post by:
Ok, so you know my problem, java is running out of memory reading with SAX, the event-based xml parser intended more-so than DOM for extremely large files. I'll try to explain what I've been doing and why I have to do it. Hopefully someone has a suggestion... Alright, so I'm using a gps-simulation program that outputs gps data, like longitude, lattitude, altitude, etc. (hundreds of terms, these are just the well known ones). In the newer...
6
3526
by: efrenba | last post by:
Hi, I came from delphi world and now I'm doing my first steps in C++. I'm using C++builder because its ide is like delphi although I'm trying to avoid the vcl. I need to insert new features to an old program that I wrote in delphi and it's a good opportunity to start with c++.
0
8687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8617
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9174
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9035
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8884
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7751
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5875
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2347
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2009
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.