Re: reading text files

From: Malcolm (malcolm_at_55bank.freeserve.co.uk)
Date: 12/11/04


Date: Sat, 11 Dec 2004 14:04:16 -0000


"EkteGjetost" <cheesemaker@gmail.com> wrote

> #include <stdio.h>
> #include <ctype.h>
>
> void countAlpha (FILE *infile, FILE *outfile, char alphabet);
> void countDigit (FILE *infile, FILE *outfile, char numbers);
> void countPunct (FILE *infile, FILE *outfile, char punctuation;
> void countSpace (FILE *infile, FILE *outfile, char spaces);
>
> int main()
>
Why not pass in the file as a parameter?

int main(int argc, char **argv)
{
   FILE *fpin;
   if(argc != 2)
   {
      /* write a function that prints out a message about how to use the
program*/
      usage();
      exit(EXIT_FAILURE);
   }

   /* open the file */
   fpin = fopen(argv[1], "r");

   /* rest of program here */
}
>
> {
> FILE *infile;
> FILE *outfile;
> char alphabet = 0;
> char numbers = 0;
> char punctuation = 0;
> char spaces = 0;
>
> infile = fopen( "input.txt", "r");
> if(infile == NULL)
> {
> printf("Cannot read input file: input.txt\n");
> return 100;
> }
> outfile = fopen( "output.txt", "w");
> if(outfile == NULL)
> {
> printf("Cannot open outputfile: output.txt\n");
> return 100;
> }
>

> countAlpha(infile, outfile, alphabet);
> countDigit(infile, outfile, numbers);
> countPunct(infile, outfile, punctuation);
> countSpace(infile, outfile, spaces);

The problem with this is that you are trying to parse the same stream four
times.

A better way is to declare a buffer of 1024 bytes. Then call fgets(). If the
line is longer than 1024 characters there will be no newline in the end.
This probably indicates a corrupt file, so you can reject it (you might need
to check max line length with whoever wrote the spec).

Then write four functions
int countAlpha(const char *line);
int countDigit(const char *line);

etc

call each function on the lines you input, and keep four running totals.
Then output at the end.

> return 0;
> }
>
> void countAlpha (FILE *infile, FILE *outfile, char alphabet)
> {
> fscanf(infile, "%c", alphabet);
>
> while(isalpha(alphabet));
> alphabet=getchar();
> // i'm pretty sure this while loop is where the problem is
>
> fprintf(outfile, "Alphabetic Characters: %c\n", alphabet);
>
> and i just repeated the same things basically for each function after
> that.
>
> When i try to run this i get an error before what seems like anything else
> happens.
>



Relevant Pages