/* Program to generate a file called "ascii" containing a table of ASCII codes. This requires a computer using ASCII codes in order to work correctly. */ /* We use the fact that the first printable ASCII character is the space, and the last is '~'. For other character code conventions (such as EBCDIC), this must be changed. */ #define FIRSTCHAR (' ') #define LASTCHAR ('~') #include #include void create_table(FILE *f); main() { /* Step 1: declare the FILE pointer. */ FILE *outfile; /* Step 2a: attempt to open the file for writing. */ outfile = fopen("ascii", "w"); /* Note: first parameter is file name, second is access mode ("w" means "write"). */ /* Step 2b: check whether we succeeded in opening the file. */ if (outfile == NULL) { printf("ERROR: Could not open file \"ascii\"\n"); exit(EXIT_FAILURE); } /* (Here we are sure the file is open for writing.) Step 3: Write all required information to the file. */ create_table(outfile); /* Step 4: close the file. */ fclose(outfile); /* At this point, the completed file should exist on the disk. */ return 0; } /******* create_table ******** Creates a table showing ASCII codes for all printable characters in five columns, with headings. On Entry: 'outfile' must refer to a file correctly opened for output. The file must not end with a partially-complete output line. On Exit: The table will be appended to the file, which is still open. */ void create_table(FILE * outfile) { int ch, i; /* Heading */ fprintf ( outfile, "char code char code char code char code char code\n" "==== ==== ==== ==== ==== ==== ==== ==== ==== ====\n" ); /* Detail lines. 'ch' is the character code, i is the number printed so far (used to break lines every five characters. */ i = 0; for (ch=FIRSTCHAR; ch<=LASTCHAR; ch++) { fprintf(outfile, " '%c' %3d", ch, ch); /* write char and code */ i++; /* That's one more! */ if (i % 5 == 0) { /* Even multiple of 5 */ putc('\n', outfile); /* Puts a single char */ } else { fputs(" ", outfile); /* Puts a string */ } } putc('\n', outfile); /* Ensure final line complete */ }