home *** CD-ROM | disk | FTP | other *** search
/ Software of the Month Club 1995 December / SOFM_Dec1995.bin / pc / dos / gi / ctutor / chap10.txt < prev    next >
Text File  |  1995-10-31  |  18KB  |  454 lines

  1.                        Chapter 10 - File Input/Output
  2.  
  3.  
  4.                               OUTPUT TO A FILE
  5.  
  6.              Load  and  display  the file named FORMOUT.C  for  your
  7.         first example of writing data to a file.  We begin as before
  8.         with the "include" statement for "stdio.h", then define some
  9.         variables for use in the example including a rather  strange
  10.         looking new type.
  11.  
  12.              The  type  "FILE"  is used for a file variable  and  is
  13.         defined in the "stdio.h" file.   It is used to define a file
  14.         pointer  for use in file operations.   The definition  of  C
  15.         contains  the requirement for a pointer to a "FILE",  and as
  16.         usual, the name can be any valid variable name.
  17.  
  18.                                OPENING A FILE
  19.  
  20.              Before we can write to a file,  we must open it.   What
  21.         this  really means is that we must tell the system  that  we
  22.         want  to  write to a file and what the filename is.   We  do
  23.         this with the "fopen" function illustrated in the first line
  24.         of the program.   The file pointer, "fp" in our case, points
  25.         to   the  file  and  two  arguments  are  required  in   the
  26.         parentheses,  the filename first, followed by the file type.
  27.         The filename is any valid DOS filename, and can be expressed
  28.         in  upper  or lower case letters,  or even mixed if  you  so
  29.         desire.   It is enclosed in double quotes.  For this example
  30.         we have chosen the name TENLINES.TXT.   This file should not
  31.         exist  on your disk at this time.   If you have a file  with
  32.         this  name,  you should change its name or move  it  because
  33.         when  we execute this program,  its contents will be erased.
  34.         If you don't have a file by this name,  that is good because
  35.         we will create one and put some data into it.
  36.  
  37.                                READING ("r")
  38.  
  39.              The  second parameter is the file attribute and can  be
  40.         any  of three letters, "r", "w", or "a", and must  be  lower
  41.         case. There are actually additional cases available in Turbo
  42.         C to allow more flexible I/O.  These are defined on page  95
  43.         of  the Turbo C Reference Guide.  When an "r" is  used,  the
  44.         file is opened for reading, a "w" is used to indicate a file
  45.         to be used for writing, and an "a" indicates that you desire
  46.         to append additional data to the data already in an existing
  47.         file.   Opening  a file for reading requires that  the  file
  48.         already exist.  If it does not exist, the file pointer  will
  49.         be set to NULL and can be checked by the program.
  50.  
  51.                                WRITING ("w")
  52.  
  53.              When  a file is opened for writing,  it will be created
  54.         if it does not already exist and it will be reset if it does
  55.  
  56.  
  57.                                    Page 69
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.                        Chapter 10 - File Input/Output
  68.  
  69.  
  70.         resulting in deletion of any data already there.
  71.  
  72.                               APPENDING ("a")
  73.  
  74.              When a file is opened for appending, it will be created
  75.         if it does not already exist and it will be initially empty.
  76.         If  it does exist,  the data input point will be the end  of
  77.         the  present data so that any new data will be added to  any
  78.         data that already exists in the file.
  79.  
  80.                            OUTPUTTING TO THE FILE
  81.  
  82.              The  job of actually outputting to the file  is  nearly
  83.         identical  to  the  outputting we have already done  to  the
  84.         standard output device.   The only real differences are  the
  85.         new  function names and the addition of the file pointer  as
  86.         one  of  the function arguments.   In the  example  program,
  87.         "fprintf" replaces our familiar "printf" function name,  and
  88.         the  file  pointer  defined earlier is  the  first  argument
  89.         within  the  parentheses.   The remainder of  the  statement
  90.         looks  like,  and  in  fact is identical  to,  the  "printf"
  91.         statement.
  92.  
  93.                                CLOSING A FILE
  94.  
  95.              To close a file,  you simply use the function  "fclose"
  96.         with the file pointer in the parentheses.  Actually, in this
  97.         simple  program,  it  is  not necessary to  close  the  file
  98.         because   the  system  will  close  all  open  files  before
  99.         returning to DOS.  It would be good programming practice for
  100.         you to get in the habit of closing all files in spite of the
  101.         fact  that they will be closed automatically,  because  that
  102.         would act as a reminder to you of what files are open at the
  103.         end of each program.
  104.  
  105.              You can open a file for writing,  close it,  and reopen
  106.         it  for  reading,  then  close it,  and open  it  again  for
  107.         appending,  etc.   Each time you open it,  you could use the
  108.         same file pointer,  or you could use a different  one.   The
  109.         file  pointer  is simply a tool that you use to point  to  a
  110.         file and you decide what file it will point to.
  111.  
  112.              Compile  and run this program.   When you run  it,  you
  113.         will  not  get any output to the monitor because it  doesn't
  114.         generate any.   After running it, look at your directory for
  115.         a file named TENLINES.TXT and "type" it.  That is where your
  116.         output will be.   Compare the output with that specified  in
  117.         the program.  It should agree.
  118.  
  119.              Do not erase the file named TENLINES.TXT yet.   We will
  120.         use it in some of the other examples in this chapter.
  121.  
  122.  
  123.                                    Page 70
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.                        Chapter 10 - File Input/Output
  134.  
  135.  
  136.  
  137.  
  138.                   OUTPUTTING A SINGLE CHARACTER AT A TIME
  139.  
  140.              Load the next example file,  CHAROUT.C,  and display it
  141.         on your monitor.  This program will illustrate how to output
  142.         a single character at a time.
  143.  
  144.              The  program begins with the "include" statement,  then
  145.         defines  some variables including a file pointer.   We  have
  146.         called the file pointer "point" this time, but we could have
  147.         used any other valid variable name.  We then define a string
  148.         of characters to use in the output function using a "strcpy"
  149.         function.   We are ready to open the file for appending  and
  150.         we  do so in the "fopen" function,  except this time we  use
  151.         the  lower cases for the filename.   This is done simply  to
  152.         illustrate  that  DOS  doesn't care about the  case  of  the
  153.         filename.  Notice that the file will be opened for appending
  154.         so  we  will  add  to the lines  inserted  during  the  last
  155.         program.
  156.  
  157.              The  program is actually two nested "for"  loops.   The
  158.         outer  loop  is  simply a count to ten so that  we  will  go
  159.         through the inner loop ten times.   The inner loop calls the
  160.         function  "putc" repeatedly until a character in "others" is
  161.         detected to be a zero.
  162.  
  163.                             THE "putc" FUNCTION
  164.  
  165.              The  part  of the program we are interested in  is  the
  166.         "putc" function.   It outputs one character at a  time,  the
  167.         character  being  the first argument in the parentheses  and
  168.         the  file pointer being the second and last  argument.   Why
  169.         the  designer of C made the pointer first in  the  "fprintf"
  170.         function, and last in the "putc" function is a good question
  171.         for which there may be no answer.   It seems like this would
  172.         have been a good place to have used some consistency.
  173.  
  174.              When  the textline "others" is exhausted,  a newline is
  175.         needed because a newline was not included in the  definition
  176.         above.   A  single "putc" is then executed which outputs the
  177.         "\n" character to return the carriage and do a linefeed.
  178.  
  179.              When  the outer loop has been executed ten  times,  the
  180.         program  closes the file and terminates.   Compile  and  run
  181.         this  program but once again there will be no output to  the
  182.         monitor.
  183.  
  184.              Following  execution  of the program,  "type" the  file
  185.         named  TENLINES.TXT and you will see that the 10  new  lines
  186.         were  added to the end of the 10 that already  existed.   If
  187.  
  188.  
  189.                                    Page 71
  190.  
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.                        Chapter 10 - File Input/Output
  200.  
  201.  
  202.         you run it again,  yet another 10 lines will be added.  Once
  203.         again,  do  not  erase  this file because we are  still  not
  204.         finished with it.
  205.  
  206.                                READING A FILE
  207.  
  208.              Load  the file named READCHAR.C and display it on  your
  209.         monitor. This is our first program to read a file.
  210.  
  211.              This program begins with the familiar  "include",  some
  212.         data  definitions,  and  the  file opening  statement  which
  213.         should  require no explanation except for the fact  that  an
  214.         "r"  is  used  here because we want to  read  it.   In  this
  215.         program,  we  check to see that the file exists,  and if  it
  216.         does,  we  execute  the  main body of the  program.   If  it
  217.         doesn't,  we print a message and quit.  If the file does not
  218.         exist,  the system will set the pointer equal to NULL  which
  219.         we can test.
  220.  
  221.              The  main body of the program is one "do while" loop in
  222.         which a single character is read from the file and output to
  223.         the monitor until an EOF (end of file) is detected from  the
  224.         input  file.   The  file is then closed and the  program  is
  225.         terminated.
  226.  
  227.                          CAUTION  CAUTION  CAUTION
  228.  
  229.              At  this  point, we have the potential for one  of  the
  230.         most  common and most perplexing problems of programming  in
  231.         C.   The  variable returned from the "getc"  function  is  a
  232.         character,  so  we  could use a  "char"  variable  for  this
  233.         purpose.   There is a problem that could develop here if  we
  234.         happened to use an "unsigned char" however, because Turbo  C
  235.         returns  a minus one which an "unsigned char" type  variable
  236.         is  not  capable  of containing.   An "unsigned  char"  type
  237.         variable can only have the values of zero to 255, so it will
  238.         return  a  255 for a minus one in Turbo C.  This is  a  very
  239.         frustrating problem to try to find.  The program simply  can
  240.         never  find the EOF and will therefore never  terminate  the
  241.         loop.   This is easy to prevent, always use an  "char"  type
  242.         variable for use in returning an EOF.
  243.  
  244.              There is another problem with this program but we  will
  245.         worry  about it when we get to the next program and solve it
  246.         with the one following that.
  247.  
  248.              After  you  compile  and  run  this  program  and   are
  249.         satisfied  with the results,  it would be a good exercise to
  250.         change the name of "TENLINES.TXT" and run the program  again
  251.         to see that the NULL test actually works as stated.  Be sure
  252.  
  253.  
  254.  
  255.                                    Page 72
  256.  
  257.  
  258.  
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.                        Chapter 10 - File Input/Output
  266.  
  267.  
  268.         to  change  the name back because we are still not  finished
  269.         with "TENLINES.TXT".
  270.  
  271.                           READING A WORD AT A TIME
  272.  
  273.              Load  and  display  the file named  READTEXT.C  for  an
  274.         example of how to read a word at a time.
  275.  
  276.              This  program  is nearly identical as the  last  except
  277.         that  this program uses the "fscanf" function to read  in  a
  278.         string  at  a  time.   Because the "fscanf"  function  stops
  279.         reading  when it finds a space or a  newline  character,  it
  280.         will read a word at a time, and display the results one word
  281.         to  a line.   You will see this when you compile and run it,
  282.         but first we must examine a programming problem.
  283.  
  284.                              THIS IS A PROBLEM
  285.  
  286.              Inspection of the program will reveal that when we read
  287.         data in and detect the EOF, we print out something before we
  288.         check  for the EOF resulting in an extra line  of  printout.
  289.         What  we usually print out is the same thing printed on  the
  290.         prior  pass  through  the loop because it is  still  in  the
  291.         buffer "oneword".  We therefore must check for EOF before we
  292.         execute  the  "printf"  function.   This has  been  done  in
  293.         READGOOD.C,  which  you will shortly examine,  compile,  and
  294.         execute.
  295.  
  296.              Compile  and execute the original program we have  been
  297.         studying, READTEXT.C and observe the output.  If you haven't
  298.         changed  TENLINES.TXT you will end up with "Additional"  and
  299.         "lines."  on  two  separate lines  with  an  extra  "lines."
  300.         displayed because of the "printf" before checking for EOF.
  301.  
  302.              Compile  and  execute READGOOD.C and observe  that  the
  303.         extra  "lines." does not get displayed because of the  extra
  304.         check for the EOF in the middle of the loop.   This was also
  305.         the problem referred to when we looked at READCHAR.C,  but I
  306.         chose  not  to expound on it there because the error in  the
  307.         output was not so obvious.
  308.  
  309.                         FINALLY, WE READ A FULL LINE
  310.  
  311.              Load and display the file READLINE.C for an example  of
  312.         reading  a complete line.   This program is very similar  to
  313.         those we have been studying except for the addition of a new
  314.         quantity, the NULL.
  315.  
  316.              We  are  using "fgets" which reads in an  entire  line,
  317.         including  the newline character into a buffer.   The buffer
  318.         to be read into is the first argument in the function  call,
  319.  
  320.  
  321.                                    Page 73
  322.  
  323.  
  324.  
  325.  
  326.  
  327.  
  328.  
  329.  
  330.  
  331.                        Chapter 10 - File Input/Output
  332.  
  333.  
  334.         and  the maximum number of characters to read is the  second
  335.         argument,  followed by the file pointer.  This function will
  336.         read  characters into the input buffer until it either finds
  337.         a  newline  character,  or it reads the  maximum  number  of
  338.         characters  allowed minus one.   It leaves one character for
  339.         the end of string NULL character.   In addition, if it finds
  340.         an  EOF,  it will return a value of NULL.   In our  example,
  341.         when the EOF is found,  the pointer "c" will be assigned the
  342.         value  of NULL.   NULL is defined as zero in your  "stdio.h"
  343.         file.
  344.  
  345.              When  we find that "c" has been assigned the  value  of
  346.         NULL,  we can stop processing data, but we must check before
  347.         we print just like in the last program.
  348.  
  349.              Last of course, we close the file.
  350.  
  351.                        HOW TO USE A VARIABLE FILENAME
  352.  
  353.              Load  and display the file ANYFILE.C for an example  of
  354.         reading  from any file.   This program asks the user for the
  355.         filename desired,  reads in the filename and opens that file
  356.         for reading.   The entire file is then read and displayed on
  357.         the   monitor.    It  should  pose  no  problems   to   your
  358.         understanding so no additional comments will be made.
  359.  
  360.              Compile  and  run  this program.   When it  requests  a
  361.         filename,  enter  the  name and extension of any  text  file
  362.         available, even one of the example C programs.
  363.  
  364.                               HOW DO WE PRINT?
  365.  
  366.              Load  the  last example file in this chapter,  the  one
  367.         named  PRINTDAT.C  for an example of  how  to  print.   This
  368.         program  should not present any surprises to you so we  will
  369.         move very quickly through it.
  370.  
  371.              Once  again,  we  open TENLINES.TXT for reading and  we
  372.         open PRN for writing.  Printing is identical to writing data
  373.         to  a disk file except that we use a standard name  for  the
  374.         filename.  Turbo C uses the reserved "filename" of PRN  that
  375.         instructs the compiler to send the output to the printer.
  376.  
  377.              The  program is simply a loop in which a  character  is
  378.         read, and if it is not the EOF, it is displayed and printed.
  379.         When the EOF is found, the input file and the printer output
  380.         files are both closed.
  381.  
  382.              You can now erase TENLINES.TXT from your disk.  We will
  383.         not be using it in any of the later chapters.
  384.  
  385.  
  386.  
  387.                                    Page 74
  388.  
  389.  
  390.  
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.                        Chapter 10 - File Input/Output
  398.  
  399.  
  400.  
  401.         PROGRAMMING EXERCISES
  402.  
  403.         1.   Write a program  that will prompt for a filename for  a
  404.              read file,  prompt for a filename for a write file, and
  405.              open both plus a file to the printer. Enter a loop that
  406.              will read a character,  and output it to the file,  the
  407.              printer, and the monitor. Stop at EOF.
  408.  
  409.         2.   Prompt for a  filename to read. Read the file a line at
  410.              a time and display it on the monitor with line numbers.
  411.  
  412.  
  413.  
  414.  
  415.  
  416.  
  417.  
  418.  
  419.  
  420.  
  421.  
  422.  
  423.  
  424.  
  425.  
  426.  
  427.  
  428.  
  429.  
  430.  
  431.  
  432.  
  433.  
  434.  
  435.  
  436.  
  437.  
  438.  
  439.  
  440.  
  441.  
  442.  
  443.  
  444.  
  445.  
  446.  
  447.  
  448.  
  449.  
  450.  
  451.  
  452.  
  453.                                    Page 75
  454.