home *** CD-ROM | disk | FTP | other *** search
/ CP/M / CPM_CDROM.iso / mbug / mbug063.arc / CHAP10.TXT < prev    next >
Text File  |  1979-12-31  |  18KB  |  455 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.   When an "r" is used, the file is opened for reading, 
  42.         a "w" is used to indicate a file to be used for writing, and 
  43.         an  "a" indicates that you desire to append additional  data 
  44.         to the data already in an existing file.  Opening a file for 
  45.         reading  requires that the file already exist.   If it  does 
  46.         not exist,  the file pointer will be set to NULL and can  be 
  47.         checked by the program. 
  48.  
  49.                                WRITING ("w")
  50.  
  51.              When  a file is opened for writing,  it will be created 
  52.         if it does not already exist and it will be reset if it does 
  53.         resulting in deletion of any data already there. 
  54.  
  55.  
  56.  
  57.                                    Page 66
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.                        Chapter 10 - File Input/Output
  68.  
  69.  
  70.                               APPENDING ("a")
  71.  
  72.              When a file is opened for appending, it will be created 
  73.         if it does not already exist and it will be initially empty.  
  74.         If  it does exist,  the data input point will be the end  of 
  75.         the  present data so that any new data will be added to  any 
  76.         data that already exists in the file.
  77.  
  78.                            OUTPUTTING TO THE FILE
  79.  
  80.              The  job of actually outputting to the file  is  nearly 
  81.         identical  to  the  outputting we have already done  to  the 
  82.         standard output device.   The only real differences are  the 
  83.         new  function names and the addition of the file pointer  as 
  84.         one  of  the function arguments.   In the  example  program, 
  85.         "fprintf" replaces our familiar "printf" function name,  and 
  86.         the  file  pointer  defined earlier is  the  first  argument 
  87.         within  the  parentheses.   The remainder of  the  statement 
  88.         looks  like,  and  in  fact is identical  to,  the  "printf" 
  89.         statement.
  90.  
  91.                                CLOSING A FILE
  92.  
  93.              To close a file,  you simply use the function  "fclose" 
  94.         with the file pointer in the parentheses.  Actually, in this 
  95.         simple  program,  it  is  not necessary to  close  the  file 
  96.         because   the  system  will  close  all  open  files  before 
  97.         returning to DOS.  It would be good programming practice for 
  98.         you to get in the habit of closing all files in spite of the 
  99.         fact  that they will be closed automatically,  because  that 
  100.         would act as a reminder to you of what files are open at the 
  101.         end of each program.
  102.  
  103.              You can open a file for writing,  close it,  and reopen 
  104.         it  for  reading,  then  close it,  and open  it  again  for 
  105.         appending,  etc.   Each time you open it,  you could use the 
  106.         same file pointer,  or you could use a different  one.   The 
  107.         file  pointer  is simply a tool that you use to point  to  a 
  108.         file and you decide what file it will point to.
  109.  
  110.              Compile  and run this program.   When you run  it,  you 
  111.         will  not  get any output to the monitor because it  doesn't 
  112.         generate any.   After running it, look at your directory for 
  113.         a file named TENLINES.TXT and "type" it.  That is where your 
  114.         output will be.   Compare the output with that specified  in 
  115.         the program.  It should agree.
  116.  
  117.              Do not erase the file named TENLINES.TXT yet.   We will 
  118.         use it in some of the other examples in this chapter.
  119.  
  120.  
  121.  
  122.  
  123.                                    Page 67
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.                        Chapter 10 - File Input/Output
  134.  
  135.  
  136.                   OUTPUTTING A SINGLE CHARACTER AT A TIME
  137.  
  138.              Load the next example file,  CHAROUT.C,  and display it 
  139.         on your monitor.  This program will illustrate how to output 
  140.         a single character at a time.
  141.  
  142.              The  program begins with the "include" statement,  then 
  143.         defines  some variables including a file pointer.   We  have 
  144.         called the file pointer "point" this time, but we could have 
  145.         used any other valid variable name.  We then define a string 
  146.         of characters to use in the output function using a "strcpy" 
  147.         function.   We are ready to open the file for appending  and 
  148.         we  do so in the "fopen" function,  except this time we  use 
  149.         the  lower cases for the filename.   This is done simply  to 
  150.         illustrate  that  DOS  doesn't care about the  case  of  the 
  151.         filename.  Notice that the file will be opened for appending 
  152.         so  we  will  add  to the lines  inserted  during  the  last 
  153.         program.
  154.  
  155.              The  program is actually two nested "for"  loops.   The 
  156.         outer  loop  is  simply a count to ten so that  we  will  go 
  157.         through the inner loop ten times.   The inner loop calls the 
  158.         function  "putc" repeatedly until a character in "others" is 
  159.         detected to be a zero.
  160.  
  161.                             THE "putc" FUNCTION
  162.  
  163.              The  part  of the program we are interested in  is  the 
  164.         "putc" function.   It outputs one character at a  time,  the 
  165.         character  being  the first argument in the parentheses  and 
  166.         the  file pointer being the second and last  argument.   Why 
  167.         the  designer of C made the pointer first in  the  "fprintf" 
  168.         function, and last in the "putc" function is a good question 
  169.         for which there may be no answer.   It seems like this would 
  170.         have been a good place to have used some consistency.
  171.  
  172.              When  the textline "others" is exhausted,  a newline is 
  173.         needed because a newline was not included in the  definition 
  174.         above.   A  single "putc" is then executed which outputs the 
  175.         "\n" character to return the carriage and do a linefeed.
  176.  
  177.              When  the outer loop has been executed ten  times,  the 
  178.         program  closes the file and terminates.   Compile  and  run 
  179.         this  program but once again there will be no output to  the 
  180.         monitor. 
  181.  
  182.              Following  execution  of the program,  "type" the  file 
  183.         named  TENLINES.TXT and you will see that the 10  new  lines 
  184.         were  added to the end of the 10 that already  existed.   If 
  185.         you run it again,  yet another 10 lines will be added.  Once 
  186.  
  187.  
  188.  
  189.                                    Page 68
  190.  
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.                        Chapter 10 - File Input/Output
  200.  
  201.  
  202.         again,  do  not  erase  this file because we are  still  not 
  203.         finished with it. 
  204.  
  205.                                READING A FILE
  206.  
  207.              Load  the file named READCHAR.C and display it on  your 
  208.         monitor. This is our first program to read a file. 
  209.  
  210.              This program begins with the familiar  "include",  some 
  211.         data  definitions,  and  the  file opening  statement  which 
  212.         should  require no explanation except for the fact  that  an 
  213.         "r"  is  used  here because we want to  read  it.   In  this 
  214.         program,  we  check to see that the file exists,  and if  it 
  215.         does,  we  execute  the  main body of the  program.   If  it 
  216.         doesn't,  we print a message and quit.  If the file does not 
  217.         exist,  the system will set the pointer equal to NULL  which 
  218.         we can test.
  219.  
  220.              The  main body of the program is one "do while" loop in 
  221.         which a single character is read from the file and output to 
  222.         the monitor until an EOF (end of file) is detected from  the 
  223.         input  file.   The  file is then closed and the  program  is 
  224.         terminated. 
  225.  
  226.                          CAUTION  CAUTION  CAUTION
  227.  
  228.              At  this point,  we have the potential for one  of  the 
  229.         most  common and most perplexing problems of programming  in 
  230.         C.   The  variable  returned from the "getc" function  is  a 
  231.         character,  so  we  could  use a "char"  variable  for  this 
  232.         purpose.   There is a problem with that however,  because on 
  233.         some,  if not most,  implementations of C, the EOF returns a 
  234.         minus  one  which a "char" type variable is not  capable  of 
  235.         containing.  A "char" type variable can only have the values 
  236.         of  zero to 255,  so it will return a 255 for a minus one on 
  237.         those  compilers that use a minus one for EOF.   This  is  a 
  238.         very   frustrating  problem  to  try  to  find  because   no 
  239.         diagnostic is given.   The program simply can never find the 
  240.         EOF  and will therefore never terminate the loop.   This  is 
  241.         easy  to prevent,  always use an "int" type variable for use 
  242.         in returning an EOF.   You can tell what your compiler  uses 
  243.         for  EOF  by  looking  at the "stdio.h" file  where  EOF  is 
  244.         defined.  That is the standard place to define such values.
  245.  
  246.              There is another problem with this program but we  will 
  247.         worry  about it when we get to the next program and solve it 
  248.         with the one following that.
  249.  
  250.              After  you  compile  and  run  this  program  and   are 
  251.         satisfied  with the results,  it would be a good exercise to 
  252.         change the name of "TENLINES.TXT" and run the program  again 
  253.  
  254.  
  255.                                    Page 69
  256.  
  257.  
  258.  
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.                        Chapter 10 - File Input/Output
  266.  
  267.  
  268.         to see that the NULL test actually works as stated.  Be sure 
  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 for the addition of a new 
  315.         quantity, the NULL.
  316.  
  317.              We  are  using "fgets" which reads in an  entire  line, 
  318.         including  the newline character into a buffer.   The buffer 
  319.  
  320.  
  321.                                    Page 70
  322.  
  323.  
  324.  
  325.  
  326.  
  327.  
  328.  
  329.  
  330.  
  331.                        Chapter 10 - File Input/Output
  332.  
  333.  
  334.         to be read into is the first argument in the function  call, 
  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.   There  are  no definite standards as far as  the 
  376.         name  or names to be used for the printer,  but some of  the 
  377.         usual names are,  "PRN",  "LPT",  "LPT1", and "LPT2".  Check 
  378.         your documentation for your particular implementation.
  379.  
  380.              Some  of  the newest compilers use  a  predefined  file 
  381.         pointer  such as "stdprn" for the print file.   Once  again, 
  382.         check your documentation.
  383.  
  384.  
  385.  
  386.  
  387.                                    Page 71
  388.  
  389.  
  390.  
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.                        Chapter 10 - File Input/Output
  398.  
  399.  
  400.              The  program is simply a loop in which a  character  is 
  401.         read, and if it is not the EOF, it is displayed and printed.  
  402.         When the EOF is found, the input file and the printer output 
  403.         files are both closed.
  404.  
  405.              You can now erase TENLINES.TXT from your disk.  We will 
  406.         not be using it in any of the later chapters.
  407.  
  408.  
  409.         PROGRAMMING EXERCISES
  410.  
  411.         1.   Write a program  that will prompt for a filename for  a 
  412.              read file,  prompt for a filename for a write file, and 
  413.              open both plus a file to the printer. Enter a loop that 
  414.              will read a character,  and output it to the file,  the 
  415.              printer, and the monitor. Stop at EOF.
  416.  
  417.         2.   Prompt for a  filename to read. Read the file a line at 
  418.              a time and display it on the monitor with line numbers.
  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 72
  454.  
  455.