ch1-copyEOF
Chapter_1 Exercise_1-7 | count Exercise_1-8 |
copyEOF.c download
#include <stdio.h> // for getchar(), putchar(), printf(), fflush(),
// stdout, EOF
#include <unistd.h> // for sleep()
#define FALSE 0
#define TRUE 1
int main() // copy input to output, then EOF (EOF is not a char, is not part of input)
{ // when reading past the last char in input, getchar() returns EOF
int c;
while ((c = getchar()) != EOF)
{putchar(c);}
do
{
printf("%d", c); // EOF as int (-1)
fflush(stdout); // flush output buffer
sleep(1); // pause for 1 second
c = getchar(); // get EOF indefinitely
} while (TRUE); // for ever
}
/*
gcc copyEOF.c -o copyEOF
./copyEOF // input from keyboard
Hello! // Enter
Hello!
// Ctrl^D in Linux, Ctrl^Z+Enter in Windows (EOF)
-1-1-1-1-1-1-1-1-1-1^C
// end with Ctrl^C
./copyEOF < copyEOF.c // redirect input to file
// end with Ctrl^C
./copyEOF < copyEOF.c > copyEOF.txt
// wait for 10 seconds, then press Ctrl^C
rm copyEOF.txt // clean
*/
Notes:
printf("%d", c);
fflush(stdout); // flush output buffer
can be replaced with
printf("%d\n", c); // flush output buffer
and then each -1 is printed
on a separate line.
EOF is defined as a macro
(in stdio.h), with value
-1
(see Exercise_4-14):
#define EOF (-1) // on disk, /usr/include/stdio.h
As such, EOF is not a character,
whose ASCII values vary between 0 and 255 (see the
ASCII_code).
The last character in a text file is usually
'\n' (newline),
with ASCII value 10
(0xA in hexadecimal).
You can verify this by opening a text file with a hexadecimal editor like
bless or
ghex.
In Linux, you can install these programs with the following commands:
sudo apt-get install bless
sudo apt-get install ghex
Alternatively, you can use a text editor like
Notepad++ and set it to
View → Show Symbol → Show All Characters (LF is
LineFeed,
newline).
Chapter_1 Exercise_1-7 | BACK_TO_TOP | count Exercise_1-8 |
Comments
Post a Comment