home *** CD-ROM | disk | FTP | other *** search
/ Simtel MSDOS 1992 September / Simtel20_Sept92.cdr / msdos / turbo_c / trboctxt.arc / CHAP10.TXT < prev    next >
Text File  |  1988-02-01  |  18KB  |  455 lines

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