Assessment Tool

Lecture 21: File Input/Output

Content Tested:  Writing a program (using files)

Lecture Content:

Goals:

Assessment Technique:  Programming Activity

Purpose:

This planning and programming activity serves to give students experience writing a program that uses functions associated with files.

Activity:

We saw in today's lecture the definition of a file and the C functions associated with manipulating a file.  Here's your opportunity to write code that accesses and writes to a file.  Given a text file called text, copy this file, double-space it, and write to to a new file called text_double.  As always, it's important to follow good design principles by stating the problem, describing the algorithm that you'll use, and then write the C code.  Since files are a new concept, you may do all the processing in the main function.  Be sure to trace the code, checking for errors and mentally testing your code.  (Hint:  To double space a file, recall that the '\n' character prints a new line.)

Problem Specification:
 
 
 
 
 

The Algorithm:
 
 
 
 
 
 
 

The C Program:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Possible Solution

#include <stdio.h>

int main (void) {
 
  /* declarations */

  FILE *infilep, *outfilep;       /* file variables */
  char ch;                        /* used as the current character */
  int status;                     /* used to check for EOF */

 
  /* open the files */
  infilep = fopen("text", "r");
  outfilep = fopen("text_double", "w");

  /* copy infile to outfile looking for \n */
  while (fscanf(infilep, "%c", &ch) != EOF){
    /* copy character to outfile */
    fprintf(outfilep, "%c", ch);
 
    /* check to see if character is '\n' -- if so, append another '\n'
       to outfile */
    if (ch == '\n'){
      fprintf(outfilep, "\n");
    }
  }

  /* close files */
  fclose(infilep);
  fclose(outfilep);

  /* return successfully */
  return 0;
}

Possible Uses of Activity: