Copy Programs |
| Copy Program in C | Copy Program in C++ |
|---|---|
/* copy.c: simplest C copy program
* copies stdin to stdout
*/
#include <stdio.h>
int main(void) {
int ch;
while ((ch = getchar()) != EOF)
putchar(ch);
}
-------------------------------------------------
% lint copy.c # try out lint
(9) warning:Function has no return statement:main
function falls off bottom without returning value
(9) main
function returns value which is always ignored
putchar
% cc -o copy copy.c
% copy # copy: terminal to terminal
Now is the time # input echoed on next line
Now is the time
for all good men ... # ditto
for all good men ...
# ctrl-d entered for end-of-file
% copy < copy.c > copy2.c # use redirection
% cat copy2.c # result of copy
/* copy.c: simplest C copy program
* copies stdin to stdout
*/
#include | // copy.cc: simplest C++ copy program
// copies cin to cout
//
#include <iostream.h>
int main() {
char ch;
while (cin.get(ch))
cout.put(ch);
}
-------------------------------------
% CC -o copy_cc copy.cc
% copy_cc
Now is the time
Now is the time
for all good men ...
for all good men ...
# ctrl-d entered for end-of-file
% copy_cc < copy.cc > copy2.cc
% cat copy2.cc
// copy.cc: simplest C++ copy program
// copies cin to cout
//
#include |
The C copy program on the left above also compiles and runs under C++, but C++ provides a different style, shown on the right above. Note that the C++ function cin.get(ch); uses a C++ reference parameter, not available in C or in Java, so that after the call, the value of the next character "pops into" the variable ch. (In C, one would have to pass the address of ch, that is &ch, and in Java this style is not possible.)
| Copy Program in Java |
|---|
// CopyFirst.java: copy standard input to standard output
import java.io.*;
class CopyFirst {
public static void main(String[] args) throws IOException {
int ch;
while ((ch = System.in.read()) != -1)
System.out.print((char)ch);
}
}
--------------------------------------------------------------
% javac CopyFirst.java
% java CopyFirst
Now is the time
Now is the time
for all good men ...
for all good men ...
# ctrl-d entered for end-of-file
% java CopyFirst < CopyFirst.java > CopyFirst2.java
% cat CopyFirst2.java
// CopyFirst.java: copy standard input to standard output
import java.io.*;
class CopyFirst {
public static void main(String[] args) throws IOException {
int ch;
while ((ch = System.in.read()) != -1)
System.out.print((char)ch);
}
}
|
The above program is not good style for input in Java, since the extra "throws" clause would be needed anywhere this input code is called from. For a through discussion of copying in Java, see: Copy programs in Java.
| Line-by-line Copy Program in C |
|---|
/* copy3.c: copy line-by-line */ #include |