Sams Teach Yourself C in 21 Days

(singke) #1
LISTINGT&R 4 Coder.c
1: /* Program: Coder.c
2: * Usage: Coder [filename] [action]
3: * where filename = filename for/with coded data
4: * where action = D for decode anything else for
5: * coding
6: *--------------------------------------------------------------*/
7:
8: #include <stdio.h>
9: #include <stdlib.h>
10: #include <string.h>
11:
12: int encode_character( int ch, int val );
13: int decode_character( int ch, int val );
14:
15: int main( int argc, char *argv[])
16: {
17: FILE *fh; /* file handle */
18: int rv = 1; /* return value */
19: int ch = 0; /* variable to hold a character */
20: unsigned int ctr = 0; /* counter */
21: int val = 5; /* value to code with */
22: char buffer[257]; /* buffer */
23:
24: if( argc != 3 )
25: {
26: printf(“\nError: Wrong number of parameters...” );
27: printf(“\n\nUsage:\n %s filename action”, argv[0]);
28: printf(“\n\n Where:”);
29: printf(“\n filename = name of file to code or decode”);
30: printf(“\n action = D for decode or C for encode\n\n”);
31: rv = -1; /* set return error value */
32: }
33: else
34: if(( argv[2][0] == ‘D’) || (argv [2][0] == ‘d’ )) /* to decode */
35: {
36: fh = fopen(argv[1], “r”); /* open the file */
37: if( fh <= 0 ) /* check for error */
38: {
39: printf( “\n\nError opening file...” );
40: rv = -2; /* set return error value */
41: }
42: else
43: {
44: ch = getc( fh ); /* get a character */
45: while( !feof( fh ) ) /* check for end of file */
46: {
47: ch = decode_character( ch, val );
48: putchar(ch); /* write the character to screen */
49: ch = getc( fh);
50: }

306 Type & Run 4

20 448201x-T&R4 8/13/02 11:12 AM Page 306

Free download pdf