home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / recio213.zip / tutor.txt < prev    next >
Text File  |  1995-09-05  |  17KB  |  458 lines

  1.     Title: A TUTORIAL INTRODUCTION TO THE C LANGUAGE RECIO LIBRARY
  2. Copyright: (C) 1994-1995, William Pierpoint
  3.   Version: 2.13
  4.      Date: September 4, 1995
  5.  
  6.  
  7.  
  8. 1.0 STDIO AND RECIO
  9.  
  10. The program many people learned when first introduced to the C programming
  11. language was the "hello, world" program published in Kernighan and Richie's
  12. "The C Programming Language."  And the first line of that first program,
  13.  
  14. #include <stdio.h>
  15.  
  16. tells the compiler that the functions and macros provided by the standard
  17. input/output library are needed for the program.  The "hello, world" program
  18. uses the powerful printf statement for output.  The counterpart for input,
  19. scanf, looks deceptively like printf, but unfortunately has many ways to
  20. trap an unwary programmer.  These include failure to provide the address
  21. of an variable, size of argument mismatched with the specification in the
  22. format statement, and number of arguments mismatched with the specification
  23. in the format statement.
  24.  
  25. Suppose you use a library that defines a boolean type as an unsigned
  26. character.  You develop an output module that writes variables of type
  27. boolean to a file,
  28.  
  29.     /* output */
  30.     boolean state=0;
  31.     ...
  32.     fprintf(fp, "%6d", state);
  33.  
  34. where fp is a pointer to FILE.  Once you get the output module working, you
  35. decide to develop the input module to read back into the program the data
  36. you wrote to disk.
  37.  
  38.     /* input */
  39.     boolean state;
  40.     ...
  41.     fscanf(fp, "%d", &state);
  42.  
  43. So, is this ok?  On one compiler this worked consistently without problems,
  44. but on another compiler, it overwrote the value in another variable.  Why?
  45. Because fscanf expects the address of an integer, not an unsigned char.
  46. One compiler overwrote the adjoining memory address and the other compiler
  47. apparently did not.  And since compilers don't do type checking on functions
  48. with variable number of arguments, you don't get any errors or warnings.  That
  49. is what is so infuriating about this type of error.  You see that another
  50. variable has the wrong value, you check all the code that uses the other
  51. variable, and you can't find anything wrong with it.  In the midst of
  52. development, it is hard to imagine that the problem is caused by code that
  53. has nothing to do with the variable containing the bad value.
  54.  
  55. The recio (record input/output) library takes a different approach to input.
  56. To input the boolean variable using the recio library, just write
  57.  
  58.     /* input */
  59.     boolean state;
  60.     ...
  61.     state = rgeti(rp);
  62.  
  63. where rp is a pointer to REC (the recio structure analogous to the stdio 
  64. FILE structure).  The rgeti function gets an integer from the input and the 
  65. compiler converts it to a boolean when it makes the assignment.  No need to 
  66. worry about crazy pointers here!
  67.  
  68. Since virtually every program has to do input or output, the stdio library
  69. is very familiar to C programmers.  Many functions in the recio library
  70. are analogous to the stdio library.  This makes the learning curve easier.
  71.  
  72.         Analogous stdio/recio components
  73.  
  74.     stdio        recio
  75.     ---------    ---------
  76.     FILE        REC
  77.     FOPEN_MAX    ROPEN_MAX
  78.  
  79.     stdin        recin
  80.     stdout        recout
  81.     stderr        recerr
  82.     stdprn        recprn
  83.  
  84.     fopen        ropen
  85.     fclose        rclose
  86.     fgets        rgetrec
  87.     fscanf        rgeti, rgetd, rgets, ...
  88.     fprintf         rputi, rputd, rputs, ...
  89.     clearerr    rclearerr
  90.     fgetpos        rgetfldpos
  91.     fsetpos        rsetfldpos
  92.     feof        reof
  93.     ferror        rerror
  94.  
  95.  
  96. 2.0 EXAMPLES
  97.  
  98. 2.1 Line Input
  99.  
  100. One of the first things you can do with the recio library to is to substitute
  101. rgetrec() for fgets() to get a line of text (record) from a file (or standard
  102. input).  The advantage of rgetrec() is that you don't have to go to the
  103. trouble to allocate space for a string buffer, or worry about the size of the
  104. string buffer.  The recio library handles that for you automatically.  The
  105. rgetrec function is like fgets() in that it gets a string from a stream, but
  106. it is like gets() in that it trims off the trailing newline character.
  107.  
  108. The echo program demonstrates the use of the rgetrec function.
  109.  
  110. /* echo.c - echo input to output */
  111.  
  112. #include <stdio.h>
  113. #include <stdlib.h>
  114.  
  115. #include "recio.h"
  116.  
  117. main()
  118. {
  119.     /* while input continues to be available */
  120.     while (rgetrec(recin)) {
  121.  
  122.         /* echo record buffer to output */
  123.         puts(rrecs(recin));
  124.     }
  125.  
  126.     /* if exited loop before end-of-file */
  127.     if (!reof(recin)) {
  128.         exit (EXIT_FAILURE);
  129.     }
  130.     return (EXIT_SUCCESS);
  131. }
  132.  
  133. The echo program reads standard input using recin, the recio equivalent to
  134. stdin.  For output the recio library provides recout, recerr, and recprn.
  135.  
  136. The rgetrec function returns a pointer to the record buffer, but the echo
  137. program did not use a variable to hold a pointer to the string (although
  138. it could have).  Instead, the record buffer was accessed through the rrecs
  139. macro, which provides a pointer to the record buffer.
  140.  
  141. Since rgetrec returns NULL on either error or end-of-file, your program
  142. needs to find out which condition occurred.  You can use either the reof
  143. function or the rerror function to determine this.  The echo program uses
  144. the reof function; the wc program in section 2.2 uses the rerror function.
  145. The echo program just exits with a failure status if an error occurred
  146. before the end of the file was reached.
  147.  
  148.  
  149. 2.2 Line, Word, and Character Counting
  150.  
  151. The power of the recio library comes from its facilities to break records
  152. into fields and from the many functions that operate on fields.  Because
  153. the default field delimiter is the space character (which breaks on any
  154. whitespace), the default behavior is equivalent to subdividing a line of
  155. text into words.
  156.  
  157. The wc program counts lines, words, and characters for files specified
  158. on the command line.
  159.  
  160. /* wc.c - count lines, words, characters */
  161.  
  162. #include <stdio.h>
  163. #include <stdlib.h>
  164. #include <string.h>
  165.  
  166. #include "recio.h"
  167.  
  168. main(int argc, char *argv[])
  169. {
  170.     int  nf;    /* number of files */
  171.     REC *rp;    /* pointer to open record stream */
  172.     long nc,    /* number of characters (not including line terminator) */
  173.          nw,    /* number of words */
  174.          nl;    /* number of lines */
  175.  
  176.     /* loop through all files */
  177.     for (nf=1; nf < argc; nf++) {
  178.  
  179.         /* open record stream */
  180.         rp = ropen(argv[nf], "r");
  181.         if (!rp) {
  182.             if (errno == ENOENT) {
  183.                 printf("ERROR: Could not open %s\n", argv[nf]);
  184.                 continue;
  185.             } else {
  186.                 printf("FATAL ERROR: %s\n", strerror(errno));
  187.                 exit (EXIT_FAILURE);
  188.             }
  189.         }
  190.  
  191.         /* initialize */
  192.         nc = nw = 0;
  193.         rsetfldch(rp, ' ');
  194.         rsettxtch(rp, ' ');
  195.  
  196.         /* loop through all lines (records) */
  197.         while (rgetrec(rp)) {
  198.  
  199.             /* count number of characters in line w/o '\n' */
  200.             nc += strlen(rrecs(rp));
  201.  
  202.             /* count number of words (fields) */
  203.             nw += rnumfld(rp);
  204.         }
  205.  
  206.         /* if exited loop on error rather than end-of-file */
  207.         if (rerror(rp)) {
  208.             printf("ERROR reading %s - %s\n", 
  209.              rnames(rp), rerrstr(rp));
  210.             exit (EXIT_FAILURE);
  211.         }
  212.  
  213.         /* get number of lines (records) */
  214.         nl = rrecno(rp);
  215.  
  216.         /* output results */
  217.         printf("%s: %ld %ld %ld\n", rnames(rp), nl, nw, nc);
  218.  
  219.         /* close record stream */
  220.         rclose(rp);
  221.     }
  222.     return (EXIT_SUCCESS);
  223. }
  224.  
  225. If ropen() fails, the wc program goes to the trouble to check errno for
  226. ENOENT rather than just assuming that the failure was caused by a missing
  227. file.
  228.  
  229. The wc program also sets the field and text delimiters even though it is
  230. unneccessary here since they are the same as the default values.  If you
  231. wanted to read a comma-delimited file, you could set the the delimiters to
  232.  
  233.     rsetfldch(rp, ',');
  234.     rsettxtch(rp, '"');
  235.  
  236. which allows you to also read text fields containing commas by delimiting
  237. the text with quotes, such as "Hello, World."
  238.  
  239. Fields are counted using the rnumfld function, which counts all the fields 
  240. in the current record.  In reading a data file, you could use rnumfld() 
  241. to count the number of fields each time a record is read.  This would give 
  242. you a quick check that the expected number of fields was found prior to 
  243. processing the record.
  244.  
  245. The recio library gives you more control over your input data than stdio.
  246. If the last field is missing from a data file, fscanf() starts reading the
  247. next line.  In a file with a complex structure, it can be difficult to tell
  248. where you are when something goes awry.  Sometimes every record in a file 
  249. has a different format.  The recio library has functions you can use to 
  250. always find out where you are.  You only input the next record when you use 
  251. the rgetrec function.
  252.  
  253. The character count does not include any line termination characters.  The 
  254. recio library strips these out of the record buffer.
  255.  
  256.  
  257. 2.3 Field Functions
  258.  
  259. For most programs you will want to use the recio functions that read or write 
  260. data.  Functions are available to read and write integer, unsigned integer, 
  261. long, unsigned long, float, double, time (time_t and struct tm), character, 
  262. and string data types.  There are two types of field functions: those that 
  263. deal with character delimited fields (such as comma-delimited) and those that 
  264. deal with column delimited fields (such as an integer between columns 1 and 5).  
  265. Each type is further divided in two: one for numeric data in base 10 and the 
  266. other for numeric data in any base from 2 to 36.
  267.  
  268.     Class    Description
  269.    ------    -----------------------------------------------------
  270.        r     character delimited fields; numeric data in base 10
  271.       rc     column delimited fields; numeric data in base 10
  272.       rb     character delimited fields; numeric data in any base
  273.      rcb     column delimited fields; numeric data in any base
  274.  
  275. A mnemonic system makes it easy to construct the name of any function you 
  276. want.  All you need to remember is that there are four prefixes (one for each 
  277. class), two bodies (get reads data; put writes data), ten suffixes (one 
  278. for each data type), and that the rb and rcb prefixes are used only with the 
  279. i, l, ui, and ul suffixes.  
  280.  
  281.     Prefix   Body   Suffix      Prefix   Body   Suffix
  282.     ------   ----   ------      ------   ----   ------
  283.       r       get      c          rb      get      i
  284.       rc      put      d          rcb     put      l
  285.                        f                          ui
  286.                        i                          ul
  287.                        l
  288.                        s
  289.                        t
  290.                       tm
  291.                       ui
  292.                       ul
  293.  
  294. Example:  The rbgetui() function takes record pointer and base arguments,
  295.           and returns an unsigned integer.
  296.  
  297. Additional information on these functions is found in the text file SPEC.TXT.
  298.  
  299.  
  300. 2.4 Error Handling
  301.  
  302. Rather than checking errno and rerror() for errors after each call to a recio
  303. function, or checking the return value from those functions that return an
  304. error value, you can register a callback error function using the rseterrfn
  305. function.  The error function gives you one convenient place to handle all
  306. recio errors.  As you write your error function, you will find that the recio
  307. library provides many useful functions for determining and reporting the
  308. location and type of error.
  309.  
  310. The dif program reads through two files line by line looking for the first 
  311. difference between the two files.  It uses a very simple callback error 
  312. function that just reports the error and then exits the program.
  313.  
  314. /* dif.c - locate line where two text files first differ */
  315.  
  316. #include <errno.h>
  317. #include <stdio.h>
  318. #include <stdlib.h>
  319. #include <string.h>
  320.  
  321. #include "recio.h"
  322.  
  323. /* simple callback error function */
  324. void rerrfn(REC *rp) 
  325. {
  326.     if (risvalid(rp)) {
  327.         fprintf(stderr, "FATAL ERROR: %s - %s\n", 
  328.          rnames(rp), rerrstr(rp));
  329.     } else {
  330.         fprintf(stderr, "FATAL ERROR: %s\n", strerror(errno));
  331.     }
  332.     exit(2);
  333. }
  334.  
  335. /* file open failure error function */
  336. void fopenerr(char *filename)
  337. {
  338.     fprintf(stderr, "FATAL ERROR: %s - %s\n", 
  339.      filename, strerror(errno));
  340.     exit(2);
  341. }
  342.  
  343. int main(int argc, char *argv[])
  344. {
  345.     int errorlevel=1; /* return errorlevel (1=files different; 0=same) */
  346.     REC *rp1;         /* record pointer for first file */
  347.     REC *rp2;         /* record pointer for second file */
  348.  
  349.     if (argc != 3) {
  350.         fprintf(stderr, "Usage: dif file1 file2\n");
  351.         exit(2);
  352.     }
  353.  
  354.     /* register callback error function */
  355.     rseterrfn(rerrfn);
  356.  
  357.     /* open first record stream */
  358.     rp1 = ropen(argv[1], "r");
  359.     if (!rp1 && errno == ENOENT) fopenerr(argv[1]);
  360.  
  361.     /* open second record stream */
  362.     rp2 = ropen(argv[2], "r");
  363.     if (!rp2 && errno == ENOENT) fopenerr(argv[2]);
  364.  
  365.     /* read files line by line */
  366.     for (;;) {
  367.     
  368.         rgetrec(rp1);
  369.         rgetrec(rp2);
  370.         
  371.         /* if neither file has reached the end */
  372.         if (!reof(rp1) && !reof(rp2)) {
  373.             if (strcmp(rrecs(rp1), rrecs(rp2))) {
  374.                 printf("Files first differ at line %ld\n\n", rrecno(rp1));
  375.                 printf("%s:\n%s\n\n", rnames(rp1), rrecs(rp1));
  376.                 printf("%s:\n%s\n\n", rnames(rp2), rrecs(rp2));
  377.                 break;
  378.             }
  379.  
  380.         /* if file 1 ended first */
  381.         } else if (reof(rp1) && !reof(rp2)) {
  382.             printf("File %s ends before file %s\n\n",
  383.              rnames(rp1), rnames(rp2));
  384.             break;
  385.  
  386.         /* if file 2 ended first */
  387.         } else if (!reof(rp1) && reof(rp2)) {
  388.             printf("File %s ends before file %s\n\n",
  389.              rnames(rp2), rnames(rp1));
  390.             break;
  391.  
  392.         /* else both files have reached the end simultaneously */
  393.         } else {
  394.             printf("Files %s and %s are identical\n", 
  395.              rnames(rp1), rnames(rp2));
  396.             errorlevel = 0;
  397.             break;
  398.         }
  399.     }
  400.     rcloseall();
  401.     return errorlevel;
  402. }
  403.  
  404. One important kind of error is the data error.  Data errors occur when data
  405. values are too large or too small, when fields contain illegal characters, 
  406. or when data is missing.  Your error function can correct data errors either
  407. through algorithms (such as the rfix functions used in the test programs) 
  408. or by asking the user for a replacement value.
  409.  
  410. For an example of a callback error function that handles data errors, see 
  411. the TESTCHG.C source code.  A skeleton code structure for a callback error 
  412. function is given in the file DESIGN.TXT.
  413.  
  414.  
  415. 2.5 Warnings
  416.  
  417. Warnings are less serious than errors and for some programs you may well 
  418. decide that they do not need to be considered.  The primary differences 
  419. between errors and warnings come into play if you decide to ignore them 
  420. by not registering callback error and warning functions.  On error, the 
  421. recio library stores the error number and stops reading or writing the 
  422. record stream.  On warning, the recio library continues to read or write 
  423. the record stream, and only stores the warning number until another 
  424. warning comes along to replace it.  
  425.  
  426. If you check the error number just before closing a record stream, you get 
  427. the number of the first error encountered.  On the other hand, if you check 
  428. the warning number at this point, you get the last warning.  Warnings are 
  429. handled with a set of routines analogous to the error handling routines.
  430.  
  431. What kinds of warnings can you get?  One warning lets you know if you have 
  432. read in an empty data string.  Another warning occurs if you write to a 
  433. columnar field and the width between the columns is too small to hold the 
  434. data.  You will find some examples of callback warning functions in the 
  435. source code for the test programs.  A skeleton code structure for a callback 
  436. warning function is given in the file DESIGN.TXT.
  437.  
  438. Simple callback error and warning functions rerrmsg and rwarnmsg are now 
  439. included in the RECIO library.  In the initial prototyping stages of 
  440. development, you may wish to use these functions rather than taking the 
  441. time to develop your own functions.  Later you can substitute more robust 
  442. callback functions.
  443.  
  444.  
  445.  
  446. 3.0 WHAT NOW?
  447.  
  448. That's it for this brief introduction.  Next, if you haven't already done
  449. so, spend a few minutes running the test programs and perusing the test 
  450. source code.  Then to study the recio functions in more detail, move on to 
  451. the remaining documentation.
  452.  
  453.  
  454. 4.0 REFERENCES
  455.  
  456. Kernighan, B.W. and Ritchie, D.M.  The C Programming Language, Second
  457. Edition.  Prentice Hall, Englewood Cliffs, NJ, 1988.
  458.