ch7-cat (Concatenate files)
Chapter_7 Exercise_7-5 | Exercise_7-6 |
CONTENTS: cat1.c cat2.c
cat1.c K&R, p. 162 download
#include <stdio.h> // for printf(), fopen(), fclose(), stdin, stdout,
// getc(), putc(), FILE, EOF, NULL, FILENAME_MAX, FOPEN_MAX
void filecopy(FILE *, FILE *);
// concatenate files, version 1
int main(int argc, char *argv[])
{
// printf("FILENAME_MAX: %d\n", FILENAME_MAX);
// printf("FOPEN_MAX: %d\n", FOPEN_MAX);
FILE *fp;
if (argc == 1) // no command-line args, just program name
{ // copy standard input to standard output
filecopy(stdin, stdout);
return 0; // end program normally
}
// else
while (--argc > 0) // for all args except program name
{ // open file for reading
if ((fp = fopen(*++argv, "r")) == NULL)
{
printf("cat1: can't open \"%s\"\n", *argv);
return 1; // end program, signalling error
}
// else // fp != NULL, file open
filecopy(fp, stdout);
fclose(fp); // close file, free fp
}
return 0;
}
// copy from ifp (input) to ofp (output)
void filecopy(FILE *ifp, FILE *ofp)
{
int c;
while ((c = getc(ifp)) != EOF)
{putc(c, ofp);}
}
/*
gcc cat1.c -o cat1
./cat1
// FILENAME_MAX: 4096 // max chars in a file name
// FOPEN_MAX: 16 // max no of files open at the same time
Hello! // Enter
Hello!
What's up? // Enter
What's up?
// Ctrl^D in Linux, Ctrl^Z+Enter in Windows (EOF)
./cat1 cat1.c
./cat1 cat1.c cat1.c
*/
cat2.c K&R, p. 163 download
#include <stdio.h> // for fprintf(), fopen(), fclose(), ferror(),
// getc(), putc(), stdin, stdout, stderr, FILE, EOF, NULL
#include <stdlib.h> // for exit()
void filecopy(FILE *, FILE *);
// concatenate files, version 2
int main(int argc, char *argv[])
{
FILE *fp;
char *prog = argv[0]; // program name
if (argc == 1) // no command-line args, just program name
{ // copy standard input to standard output
filecopy(stdin, stdout);
exit(0); // end program normally
}
// else
while (--argc > 0) // for all args except program name
{ // open file for reading
if ((fp = fopen(*++argv, "r")) == NULL)
{
fprintf(stderr, "%s: can't open \"%s\"\n", prog, *argv);
exit(1); // end program, signalling error
}
// else // fp != NULL, file open
filecopy(fp, stdout);
fclose(fp); // close file, free fp
}
if (ferror(stdout))
{
fprintf(stderr, "%s: error writing stdout\n", prog);
exit(2); // end program, signal other error code
}
exit(0); // end program normally
}
// copy from ifp (input) to ofp (output)
void filecopy(FILE *ifp, FILE *ofp)
{
int c;
while ((c = getc(ifp)) != EOF)
{putc(c, ofp);}
}
/*
gcc cat2.c -o cat2
./cat2
Hello! // Enter
Hello!
What's up? // Enter
What's up?
// Ctrl^D in Linux, Ctrl^Z+Enter in Windows (EOF)
./cat2 cat2.c
./cat2 cat1.c cat2.c
*/
Chapter_7 Exercise_7-5 | BACK_TO_TOP | Exercise_7-6 |
Comments
Post a Comment