473,322 Members | 1,379 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

getchar() after EOF

If a call to getchar() returns EOF, is the behavior
defined if another getchar() call is made? Will it
return EOF again?

The reason I'm asking: if I have a function that uses
getchar() repeatedly, and it returns EOF after some bytes,
do I need the function to handle the EOF right there,
or, can I just wait until the next time my function executes,
and handle it there, if EOF will be returned by the first call
to getchar().

Thanks!

/Michael
Jun 12 '06 #1
11 4438
In article <Wz*****************@newsb.telia.net>,
Michael Brennan <br************@gmail.com> wrote:
If a call to getchar() returns EOF, is the behavior
defined if another getchar() call is made? Will it
return EOF again?
Yes. Though in my reading of C89, it might plausibly set the
error indicator as it does so.

The reason I'm asking: if I have a function that uses
getchar() repeatedly, and it returns EOF after some bytes,
do I need the function to handle the EOF right there,
or, can I just wait until the next time my function executes,
and handle it there, if EOF will be returned by the first call
to getchar().


What would you do with the EOF's returned in the itermediate
calls? If you were planning on storing them, then remember that
EOF is an int, not a char
--
I was very young in those days, but I was also rather dim.
-- Christopher Priest
Jun 12 '06 #2
> If a call to getchar() returns EOF, is the behavior
defined if another getchar() call is made? Will it
return EOF again?


7.19.7.6 of the standard says this:
"The getchar function returns the next character from the input stream
pointed to by stdin. If the stream is at end-of-file, the end-of-file
indicator for the stream is set and getchar returns EOF."

I believe that a stream, once at end-of-file remains at end-of-file
unless reverse positioning happens. However, I cannot find a direct
statement about this in the standard.
Jun 12 '06 #3
In article <e6********@dispatch.concentric.net>,
Jim Cook <co****@strobedata.com> wrote:
7.19.7.6 of the standard says this:
"The getchar function returns the next character from the input stream
pointed to by stdin. If the stream is at end-of-file, the end-of-file
indicator for the stream is set and getchar returns EOF." I believe that a stream, once at end-of-file remains at end-of-file
unless reverse positioning happens.
Though clrerror() will clear the EOF indicator as well as the
error indicator.
However, I cannot find a direct
statement about this in the standard.

--
Programming is what happens while you're busy making other plans.
Jun 12 '06 #4
Walter Roberson wrote:

What would you do with the EOF's returned in the itermediate
calls? If you were planning on storing them, then remember that
EOF is an int, not a char


My function puts chars returned by getchar() in a string and returns it.
If it encounters an EOF, I want to notify that to the caller, maybe by
returning NULL. But that won't work if I encounter the EOF directly
after some chars in the same function run since I can't return both the
string and NULL, so I've come up with three options.

1. indicate end-of-file some other way, by using an argument or
2. save the EOF in a static variable and return NULL if it is set
3. just call getchar() again the next time the function runs and return
NULL when that EOF is read.

Which one would be best of these? or is there an even better way?
Jun 12 '06 #5
Michael Brennan wrote:
Walter Roberson wrote:

What would you do with the EOF's returned in the itermediate
calls? If you were planning on storing them, then remember that
EOF is an int, not a char


My function puts chars returned by getchar() in a string and returns it.
If it encounters an EOF, I want to notify that to the caller, maybe by
returning NULL. But that won't work if I encounter the EOF directly
after some chars in the same function run since I can't return both the
string and NULL, so I've come up with three options.

1. indicate end-of-file some other way, by using an argument or
2. save the EOF in a static variable and return NULL if it is set
3. just call getchar() again the next time the function runs and return
NULL when that EOF is read.

Which one would be best of these? or is there an even better way?


None. Text files in C consist of complete lines, terminated with
'\n'. The problem does not arise when you transmit things on
encountering a '\n'. Thus:

int ch; /* note this is an int */
char buffer[SOMESIZE+1];
int i;

i = 0;
while (EOF != (ch = getchar())) {
if ('\n' == ch) {
dosomethingwith(buffer);
buffer[i] = '\0';
i = 0;
}
else if (i < SOMESIZE) buffer[i++] = ch;
else youareoverunningthebuffer();
}
/* file is all read */
--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>

Jun 12 '06 #6
CBFalconer wrote:

None. Text files in C consist of complete lines, terminated with
'\n'. The problem does not arise when you transmit things on
encountering a '\n'. Thus:
Does that mean that there always will be a '\n' before an EOF, and
that 'A','B','C',EOF will never occur?
What if the last line in a file does not end with a '\n', or
if a user signals EOF on stdin before pressing return.
Will a '\n' be appended automatically?

int ch; /* note this is an int */
char buffer[SOMESIZE+1];
int i;

i = 0;
while (EOF != (ch = getchar())) {
if ('\n' == ch) {
dosomethingwith(buffer);
buffer[i] = '\0';
i = 0;
}
else if (i < SOMESIZE) buffer[i++] = ch;
else youareoverunningthebuffer();
}
/* file is all read */

Jun 12 '06 #7
Michael Brennan <br************@gmail.com> writes:
Walter Roberson wrote:
What would you do with the EOF's returned in the itermediate
calls? If you were planning on storing them, then remember that
EOF is an int, not a char


My function puts chars returned by getchar() in a string and returns it.
If it encounters an EOF, I want to notify that to the caller, maybe by
returning NULL. But that won't work if I encounter the EOF directly
after some chars in the same function run since I can't return both the
string and NULL, so I've come up with three options.

1. indicate end-of-file some other way, by using an argument or
2. save the EOF in a static variable and return NULL if it is set
3. just call getchar() again the next time the function runs and
return NULL when that EOF is read.

Which one would be best of these? or is there an even better way?


Using a static variable can cause problems.

Note that fgets() does something very similar to what you're doing.
Take a look at what it does, and consider handling EOF in the same
way.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 12 '06 #8


CBFalconer wrote On 06/12/06 14:44,:
Michael Brennan wrote:
Walter Roberson wrote:
What would you do with the EOF's returned in the itermediate
calls? If you were planning on storing them, then remember that
EOF is an int, not a char
My function puts chars returned by getchar() in a string and returns it.
If it encounters an EOF, I want to notify that to the caller, maybe by
returning NULL. But that won't work if I encounter the EOF directly
after some chars in the same function run since I can't return both the
string and NULL, so I've come up with three options.

1. indicate end-of-file some other way, by using an argument or
2. save the EOF in a static variable and return NULL if it is set
3. just call getchar() again the next time the function runs and return
NULL when that EOF is read.

Which one would be best of these? or is there an even better way?

None. Text files in C consist of complete lines, terminated with
'\n'.


We could say that "well-formed" text files or "text files
written by portable programs" consist only of '\n'-terminated
lines, but it's a stretch to say that "all" text files are so
nicely put together. The Standard explicitly mentions the
possibility that a file of text lines might not end in '\n'
(7.19.2/2, right after it says what a "line" is).

The consequences are two: First, a portable program should
always write complete '\n'-terminated lines, because the
implementation might require the terminator and might misbehave
without it. Second, a portable program should be prepared to
deal with a text stream that lacks its final '\n', because the
implementation might allow them.
The problem does not arise when you transmit things on
encountering a '\n'.
... unless the final '\n' is missing. It "shouldn't" be
missing, but the Standard does not say that it "shall not" be
missing, so the eventuality must be considered. Some plausible
responses:

- Accept the EOF-terminated "line" as valid, and process
it like any other line. Variations: leave the line's
data "bare," or synthesize a '\n' for it. (If you like
to strip the '\n' from each normal line, distinguishing
between these variations becomes a problem for philosophers
more than for programmers.)

- Howl, complain, protest, and sulk, possibly by calling
abort() or exit(EXIT_FAILURE) or something of the kind.
Bad data (if you choose to call the '\n'-less line "bad,"
which is a reasonable choice) is bad data, and ought to
be detected and rejected.
Thus: [...]


Simply ignoring the suspect "line" and carrying on as if
everything were hunky-dory isn't a course I'd choose.

--
Er*********@sun.com

Jun 12 '06 #9
Michael Brennan <br************@gmail.com> writes:
CBFalconer wrote:
None. Text files in C consist of complete lines, terminated with
'\n'. The problem does not arise when you transmit things on
encountering a '\n'. Thus:


Does that mean that there always will be a '\n' before an EOF, and
that 'A','B','C',EOF will never occur?
What if the last line in a file does not end with a '\n', or
if a user signals EOF on stdin before pressing return.
Will a '\n' be appended automatically?


No. C99 7.19.2p2 says:

A text stream is an ordered sequence of characters composed into
*lines*, each line consisting of zero or more characters plus a
terminating new-line character. Whether the last line requires a
terminating new-line character is implementation-defined.

Unfortunately, the standard isn't clear about what's supposed to
happen in an implementation where the terminating new-line is required
if it's not actually present; presumably it's undefined behavior.

But on many systems, the terminating new-line *isn't* required. On
such a system, if you have a file consisting of the three characters
'A', 'B', and 'C' followed by end-of-file, fgets(), for example, will
give you the string "ABC" without a '\n'.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 12 '06 #10
In article <e6**********@canopus.cc.umanitoba.ca>,
Walter Roberson <ro******@ibd.nrc-cnrc.gc.ca> wrote:
If a call to getchar() returns EOF, is the behavior
defined if another getchar() call is made? Will it
return EOF again?
Yes.


But you may well find that not all the systems you have to deal with
conform to the standard in this respect. Use Google to search this
group for "eof sticky".

For historical interest, look at

http://groups.google.com/group/net.u...0d75da64c6219e

-- Richard
Jun 12 '06 #11
Michael Brennan wrote:
CBFalconer wrote:

None. Text files in C consist of complete lines, terminated with
'\n'. The problem does not arise when you transmit things on
encountering a '\n'. Thus:


Does that mean that there always will be a '\n' before an EOF, and
that 'A','B','C',EOF will never occur?
What if the last line in a file does not end with a '\n', or
if a user signals EOF on stdin before pressing return.
Will a '\n' be appended automatically?

No. However the code below will still function correctly. At exit
from the loop, if the buffer is non-empty (detected by i > 0) the
system has allowed a final line without a '\n'. Note that a file
can be empty, when the first call to getchar returns EOF. The line
"buffer[i] = '\0';" should precede "dosomethinwith(buffer);" to
ensure that buffer holds a valid C string. The code also ALWAYS
absorbs the '\n'.

int ch; /* note this is an int */
char buffer[SOMESIZE+1];
int i;

i = 0;
while (EOF != (ch = getchar())) {
if ('\n' == ch) {
dosomethingwith(buffer);
buffer[i] = '\0';
i = 0;
}
else if (i < SOMESIZE) buffer[i++] = ch;
else youareoverunningthebuffer();
}
/* file is all read */


--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>
Jun 13 '06 #12

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

Similar topics

21
by: clusardi2k | last post by:
/* The below code on SGI will wait for you to enter 2 things, but on Linux it will only wait the first time. I can make the code work by replacing the scanf with: char data ; fgets...
12
by: Emmanuel Delahaye | last post by:
Hi there, It is commonly accepted that a call to the getchar() function suspends the execution of the current program. I have not found any description of this behaviour in the standard (I may...
1
by: White Spirit | last post by:
I'm trying to use getchar() to read alphanumeric data as follows:- char input; /* Take a string of input and remove all spaces therein */ int j = 0; while ((input = getchar()) != '\n') { if...
5
by: Jonathan | last post by:
Hi-- I have the following code: #include <stdio.h> char a,b; int main()
10
by: john | last post by:
What does the standard say about getchar()? Do you have to press return to "send" the char to the program, or is it implementation defined? I read in a book that on some systems the function...
6
by: Alan | last post by:
I am using Standard C compiled with GCC under Linux Fedora Core 4 When I run this program and enter a character at the prompt, I have to press the ENTER key as well. This gives me 2 input...
11
by: shekhardeodhar | last post by:
The program compiles properly (most of it is from k&r) but the second function (here character_count) gives wrong answer. Can someone please explain why ? #include<stdio.h> #define IN 1...
25
by: ehabaziz2001 | last post by:
Why I can not begin my subscript of character arrrays with 0. In this program I can not do : do { na=getchar(); i++; na=getchar(); } while (na!='\n');
3
by: mahiapkum | last post by:
Hello, I have a code which uses getchar(). #include<stdio.h> int main() { char ch; ch = getchar(); if(ch == 'Y') { printf("Beautiful...
22
by: arnuld | last post by:
Mostly when I want to take input from stdin I use getchar() but I get this from man page itself: "If the integer value returned by getchar() is stored into a variable of type char and then...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.