Download C-Tutorial

Transcript
Using arrays and sorting 71
One of the first things to notice is that the program tests with strcmp to see if two files are the
same. This means that when the user passes the command line:
paste File1 filE1
our program will believe that they are different when in fact they are not. Windows is not case
sensitive for file names. The right thing to do there is to compare the file names with stricmp,
that ignores the differences between uppercase and lowercase.
But an even greater problem is that we do not test for NULL when opening the files. If any of
the files given in the command line doesn’t exist, the program will crash. Add the necessary
tests before you use it.
Another problem is that we test if we have the right number of arguments (i.e. at least two file
names) but if we have more arguments we simply ignore them. What is the right behavior?
Obviously we could process (and paste) several files at once. Write the necessary changes in
the code above. Note that if you want to do the program really general, you should take into
account the fact that a file could be repeated several times in the input, i.e.
paste file1 file2 file1 file3
Besides, the separator char in our program is now hardwired to the tab character in the code of
the program. Making this an option would allow to replace the tab with a vertical bar, for
instance.
But the problem with such an option is that it supposes that the output will be padded with
blanks for making the vertical bars align. Explain why that option needs a complete rewrite of
our program. What is the hidden assumption above that makes such a change impossible?
Another feature that paste.exe could have, is that column headers are automatically underlined. Explain why adding such an option is falling into the featurism that pervades all modern
software. Learn when to stop!
1.15 Using arrays and sorting
Suppose we want to display the frequencies of each letter in a given file. We want to know the
number of ‘a’s, of ‘b’, and so on.
One way to do this is to make an array of 256 integers (one integer for each of the 256 possible
character values) and increment the array using each character as an index into it. When we
see a ‘b’, we get the value of the letter and use that value to increment the corresponding position in the array. We can use the same skeleton of the program that we have just built for
counting characters, modifying it slightly.50
#include <stdio.h>
#include <stdlib.h>
int Frequencies[256]; // Array of frequencies
int main(int argc,char *argv[])
{
// Local variables declarations
int count=0;
FILE *infile;
int c;
if (argc < 2) {
50. Yes, code reuse is not only possible in object-oriented programming.