On 14 Sep 2005 21:50:22 +0200, Yandos <fa******@fakeisp.cz> wrote:
Hello all,
I have maybe a trivial question, but I cannot think out what is wrong :(
How do i detect EOF correctly when i read from stdin? Am I doing it
wrong?
<pipetest.c>
#include <stdio.h>
int main(void) {
char ch;
while (!feof(stdin)) { // <-- EOF appears to be true when character 0x1A is on stdin
ch=getchar(); // <-- variable ch has value of 0xFF when 0x1A was on stdin
putchar(ch);
}
return(0);
}
<256.tmp>
contains values from 0 to 255
I compiled and run from cmd prompt: pipetest.exe < 256.tmp > out.tmp
<out.tmp>
00000000 00 01 02 03 04 05 06 07 08 09 0D 0A 0B 0C 0E 0F
00000010 10 11 12 13 14 15 16 17 18 19 FF
Why the program ended on 0x1A character and outputted FF instead?
How do I correctly write program which can be used with pipes? I use
free borland turbo c++ 1.01 compiler on windows xp.
Thanks anyone for kind help,
Y.
First of all, both questions you posted were centered on the
(mis)behavior of a C, (not C++,) program. If you have C questions
you'll get a better responses and more patience in a C related group.
Now to your question: Borland's Turbo C++ 1.0 is an old compiler,
(I believe I bought it in 1990?) written at a time were compatibility
with MS-DOS (plain DOS, not Windows) was important. Many details of
the run time library ensure compatibility with data files created by
other DOS programs, many of which tried to be compatible with files
created under DOS, CPM-86 and CPM-80.
All these last three operating systems use a CONTROL-Z character
(0x1A) as an end-of-file marker in text files. The (historic) reason
being that CPM-80 kept track of file sizes only as the number of 128
byte blocks. To know exactly where a text file ended in the last
block, the convention of using CTRL-Z (a non-printable character) was
established.
So your program stops reading when it receives an indication it
reached the end of file. The 0xFF following it is an error code
supplied when you try to read from a file beyond the logical
end-of-file.
Also note that before reaching CTRL-Z, the newline char (0x0A) was
expanded into carriage return - newline (0x0D 0x0A) and that the
carriage return following it was discarded. Opening the file/pipe in
binary mode would correct all these problems
I am sure there must be a way of modifying your program to tell BC++
1.0 to use binary mode, but it would be a waste of time. You can get
other (more modern) free compilers, and your time would be better
spent learning to do this on LCC-Win32, Digital Mars C/C++, GCC, or
even Microsoft compilers. (They are free, not Visual Studio, but the
underlying compilers.)
Roberto Waltman
[ Please reply to the group, ]
[ return address is invalid. ]