Writing to files

The following sample program demonstrates how to write output to a file in C. The program opens an output file, and writes some output into that file, and then closes it. You can copy this program into your directory by typing the following. Be sure not to forget the dot at the end!
cp ~pconrad/public_html/cisc105/05F/lect/notes/09.21/writeToFile.c .
/* a program that just demonstrates how to write output to a file */

#include <stdio.h>

int main ()
{
  FILE *outfile;  /* declare a file pointer */
  int x=3;        /* x and y are variables just for demonstration purposes */
  double y=4.5;
  
  /* open the output file */
  
  outfile = fopen("writeToFile.dat","w"); /* try to open file for writing */
  if (outfile == NULL)               /* check return status */
    {
      perror("File writeToFile.dat could not be opened: "); /* print error */
      exit(-1);
    }
  
  /* write some output to the file */
  
  fprintf(outfile,"This output is going to the file writeToFile.dat.\n");
  
  printf("This output is going to the terminal.\n");
  printf("I can still write to the terminal in the same program\n");
  printf("that I am writing to a file.\n");
  
  fprintf(outfile,"I can also print the value of variables to a file.\n");
  fprintf(outfile,"for example, x=%d, y=%.2f\n",x,y);
  fprintf(outfile,"Bye now!\n");
  
  /* close the output file */
  
  fclose(outfile);
  
  return 0;
}


For Part1 of this lab, do the following steps. The result will be a script file writeToFile.txt, which you will submit.
  1. Copy the writeToFile.c file into your directory.
  2. Compile it, but don't run it yet.
  3. Before you run it, do an ls command, and note that there is no file called writeToFile.dat in your directory.
  4. Now run the program. Note the output you get on your screen. Then do another ls command and note that there should now be a file called writeToFile.dat in your directory. Use cat writeToFile.dat to list the output of this file.
  5. Now edit the writeToFile.c file to personalize the message that is going to the file. Make it print your name to the file as part of the message, along with any other pithy comments you want to pass along to your TA and/or instructor.
  6. Use the rm command to delete writeToFile.dat from your directory. Then, make a script file writeToFile.txt in which you
    1. cat and then compile your new (personalized) version of writeToFile.c,
    2. use ls to show that there is no writeToFile.dat file in your directory,
    3. run the program,
    4. redo the ls command to show that writeToFile.dat was created,
    5. and cat the output of your new personalized writeToFile.dat.

    You should submit writeToFile.txt as part of your submission for this week's lab. You don't need to submit the .c file, or the .dat file for this part.
`
Phillip T Conrad
Last modified: Fri Nov 21 08:48:08 EST 2003