L-35 MCS 275 Fri 6 Apr 2001

Below is the completed version of the program we discussed in class.
/* L-35 MCS 275 Fri 6 Apr 2001 : buffered read with temporary file */

/* The program below creates an output file that contains words given
   by the user.  Each line in the output file starts with the number
   of words on that line.  We use a temporary file as buffer. */

#include <stdio.h>

void buffered_read ( FILE *ofp );
/* reads words the user gives line by line,
   writes the words to the file ofp (which must be opened for output),
   each line starts with the number of words on that file */

void copy_buffer ( int cnt, FILE *buffer, FILE *ofp );
/* rewinds the buffer and copies the first line in the buffer to 
   the output file ofp, after writing the count cnt */

int count_words ( FILE *fp );
/* rewinds the file and returns the number of words on the file */

void print ( FILE *fp );
/* rewinds the file and prints the content of the file on screen */

int main ()
{
   char filename[80];
   FILE *outfile;

   printf("Give the name of the output file : ");
   scanf("%s", filename);
   scanf("%*c");                        /* skip new line symbol */

   outfile = fopen(filename,"w+");
   buffered_read(outfile);
   fclose(outfile);
   
   return 0;
}

void buffered_read ( FILE *ofp )
{
   FILE *buffer = tmpfile();
   char c;
   int cnt;

   for (;;)
   {
      printf("Give a line of words (empty line to stop) : ");
      scanf("%c", &c);
      if (c == '\n') break;
      fprintf(buffer,"%c", c);      /* copy chars read to buffer file */
      do
      {
         scanf("%c", &c);
         fprintf(buffer,"%c", c);
      }
      while (c != '\n');
 
      printf("The contents of the buffer :\n");
      print(buffer);
      cnt = count_words(buffer);
      printf("Number of words read : %d\n", cnt);
      copy_buffer(cnt,buffer,ofp);

      printf("Number of bytes in output file : %d\n", ftell(ofp));

      printf("Content of output file : \n"); print(ofp);

      rewind(buffer);               /* will cause to overwrite buffer */
   }
}

void print ( FILE *fp )
{
   char c;

   rewind(fp);
   while (fscanf(fp,"%c", &c) == 1)
      printf("%c", c);
}

int count_words ( FILE *fp )
{
   int cnt=0;
   char c;

   rewind(fp);
   c = getc(fp);

   while (c != '\n')
   {
      while (c == ' ') c = getc(fp);                  /* skip white space */
      if (c != '\n')
      {
         ++cnt;
         while ((c != ' ') && (c != '\n')) c = getc(fp);     /* skip word */
      }
   }

   return cnt;
}

void copy_buffer ( int cnt, FILE *buffer, FILE *ofp )
/* note that the buffer may contain multiple lines if the user gives
   consecutively shorter and shorter lines */
{
   char c;

   fprintf(ofp,"%d ", cnt);

   rewind(buffer);
   do
   {
      c = getc(buffer);
      putc(c,ofp);
   }
   while (c != '\n');
}