home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_10_10 / 1010067a < prev    next >
Text File  |  1992-08-11  |  2KB  |  87 lines

  1. //arts.c ...ref CUJ April 1992 page 108, the Q&A column by Ken Pugh
  2.  
  3. //select the file to be created
  4. //
  5. #define       FILE_FORMAT         "ARTS1.FF"
  6. //
  7. //nothing else in this file needs to change!
  8.  
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <conio.h>
  12.  
  13. //create structure
  14. #define ff(name,size)    char name[size+NUL_TERMINATED];
  15. struct rec{
  16. #include FILE_FORMAT
  17. };
  18.  
  19. //initialize sizes array
  20. #define ff(name,size)    size + NUL_TERMINATED,
  21. static int field_sizes[] = {
  22. #include FILE_FORMAT
  23. };
  24.  
  25. #define FIELDCOUNT  (sizeof(field_sizes)/sizeof(int))
  26.  
  27. #define TRUE  1
  28. #define FALSE 0
  29.  
  30. //build custom print function
  31. #define ff(name, size)  printf("%*s: %.*s\n", 20, #name, 
  32. size+NUL_TERMINATED, record->name );
  33. void art_print(struct rec* record)
  34. {
  35. printf("\n\n");
  36. #include FILE_FORMAT
  37. printf("\n\nPress key...");
  38. getch();
  39. }
  40.  
  41. //set arbitrary limit to record creation
  42. #define RECS 5
  43. //
  44. //generate some data
  45. void createfile(void)
  46. {
  47. int r, f;
  48. char buf[100];
  49. FILE *fp = fopen(FILENAME,"w");
  50. if(!fp){
  51.  printf("Open failed\n");
  52.  exit(1);
  53.  }
  54. for(r=0; r<RECS; r++){
  55.  for(f=0; f<FIELDCOUNT; f++){
  56.    memset(buf,'A'+f+r,field_sizes[f]);
  57.    if(NUL_TERMINATED)
  58.      buf[field_sizes[f]-1] = 0;
  59.    fwrite(&buf, sizeof(char), field_sizes[f], fp);
  60.    }
  61.  }
  62. fclose(fp);
  63. }
  64.  
  65. void stats(void){
  66. printf("\n\nStats for file '%s':\n\n", FILENAME);
  67. printf("\tStructure size %d\n", sizeof(struct rec) );
  68. printf("\tThere are %d fields\n", FIELDCOUNT);
  69. printf("\tThe fields are %snul-terminated\n",
  70.  (NUL_TERMINATED?"":"not " ));
  71. }
  72.  
  73. void main(void){
  74. struct rec record;
  75. FILE *fp;
  76.  
  77. createfile();
  78. stats();
  79. fp = fopen(FILENAME,"r");
  80. if(fp){
  81.  while(fread(&record, sizeof(record),1, fp))
  82.    art_print(&record);
  83.  fclose(fp);
  84.  }
  85. }
  86.  
  87.