473,949 Members | 24,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4498
In article <Wz************ *****@newsb.tel ia.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********@dis patch.concentri c.net>,
Jim Cook <co****@strobed ata.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 youareoverunnin gthebuffer();
}
/* file is all read */
--
"If you want to post a followup via groups.google.c om, 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/googlegroupsrep ly/>

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 youareoverunnin gthebuffer();
}
/* 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_Keit h) 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_FAILU RE) 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_Keit h) 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

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

Similar topics

21
639
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 (data,5,stdin); the_number = atoi (data);
12
4109
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 have missed it). I was wondering wether it was just a 'common' behaviour of most systems, and wether the hit of the ENTER key was mandatory. Thanks for having read me.
1
3729
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 (!isspace(input)) j++;
5
8784
by: Jonathan | last post by:
Hi-- I have the following code: #include <stdio.h> char a,b; int main()
10
6636
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 returns after you just typed the char, thus, it has no input buffer. Is that correct?
6
5301
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 characters - 'a' and '\n' (Hex 61 and 0a) It seems as though the getchar() function needs ENTER to terminate reading stdin. I am trying to get the program to respond when I press one key only (ie
11
2517
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 #define OUT 0 int word_count();
25
5477
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
12518
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 World\n");
22
3642
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 compared against the integer constant EOF, the comparison may never succeed, because sign-extension of a variable of type char on widening to integer is implementation-defined" while( EOF != (ch = getchar()) ) ....
0
10171
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
9991
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
11594
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
10701
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
9903
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...
1
8265
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6130
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4957
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3556
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.