C/File/File Read — различия между версиями

Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
(нет различий)

Версия 14:20, 25 мая 2010

Check for errors: How to use ferror

#include <stdio.h>
int main ()
{
  FILE *file;
  file = fopen("my.txt","r");
  
  if (file==NULL) 
      perror ("Error opening my.txt");
  else {
    fputc ("e",file);
    if (ferror (file))
      printf ("Error Writing to my.txt\n");
    fclose (file);
  }
  return 0;
}


Count the number of characters in a file

/*
Practical C Programming, Third Edition
By Steve Oualline
Third Edition August 1997 
ISBN: 1-56592-306-5
Publisher: O"Reilly
*/

#include <stdio.h>
const char FILE_NAME[] = "input.txt";
#include <stdlib.h> 
int main() {
    int             count = 0;  /* number of characters seen */
    FILE           *in_file;    /* input file */
    /* character or EOF flag from input */
    int             ch;
    in_file = fopen(FILE_NAME, "r");
    if (in_file == NULL) {
        printf("Cannot open %s\n", FILE_NAME);
        exit(8);
    }
    while (1) {
        ch = fgetc(in_file);
        if (ch == EOF)
            break;
        ++count;
    }
    printf("Number of characters in %s is %d\n",
                  FILE_NAME, count);
    fclose(in_file);
    return (0);
}


Create a file, write content and read the content

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  char str[80] = "This is a test.\n";
  FILE *fp;
  char *p;
  int i;
  /* open my.txt for output */
  if((fp = fopen("my.txt", "w"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  /* write str to disk */
  p = str;
  while(*p) {
    if(fputc(*p, fp)==EOF) {
      printf("Error writing file.\n");
      exit(1);
    }
    p++;
  }
  fclose(fp);
  /* open my.txt for input */
  if((fp = fopen("my.txt", "r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  /* read back the file */
  for(;;) {
     i = fgetc(fp);
     if(i == EOF) break;
     putchar(i);
  }
  fclose(fp);
  return 0;
}


fscanf() - fprintf() example

#include <stdio.h>
#include <io.h>
#include <stdlib.h>
int main(void)
{
  FILE *fp;
  char s[80];
  int t;
  if((fp=fopen("test", "w")) == NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  printf("Enter a string and a number: ");
  fscanf(stdin, "%s%d", s, &t); /* read from keyboard */
  fprintf(fp, "%s %d", s, t); /* write to file */
  fclose(fp); 
  if((fp=fopen("test","r")) == NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  fscanf(fp, "%s%d", s, &t); /* read from file */
  fprintf(stdout, "%s %d", s, t); /* print on screen */
  return 0;
}


Get a string from a stream: how to use fgets

#include <stdio.h>
int main()
{
   FILE *file;
   char string [100];
   file = fopen ("my.txt" , "r");
   if (file == NULL) 
       perror ("Error reading file");
   else {
     fgets (string , 100 , file);
     puts (string);
     fclose (file);
   }
   return 0;
}


Get string from file

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
  FILE *fp;
  char str[128];
  if((fp = fopen(argv[ 1 ], "r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  while(!feof(fp)) {
    if(fgets(str, 126, fp)) 
        printf("%s", str);
  }
  fclose(fp);
  return 0;
}


Get the next character from a stream: how to use fgetc

#include <stdio.h>
int main ()
{
  FILE * file;
  char c;
  int n = 0;
  file=fopen ("my.txt","r");
  
  if (file==NULL) 
      perror ("Error reading my.txt");
  else
  {
    do {
      c = fgetc (file);
      if (c == "$") 
          n++;
    } while (c != EOF);
    
    fclose (file);
    printf ("File contains %d $.\n",n);
  }
  return 0;
}


Get the next character: how to use getc

#include <stdio.h>
int main ()
{
  FILE *file;
  char c;
  int n = 0;
  file = fopen("my.txt", "r");
  
  if (file==NULL) 
      perror ("Error reading file");
  else
  {
    do {
      c = getc (file);
      if (c == "$") 
          n++;
      } while (c != EOF);
    fclose (file);
    printf ("my.txt contains %d $.\n",n);
  }
  return 0;
}


Get the next int value from a stream: how to use getw and putw

/* putw/getw example */
#include <stdio.h>
int main ()
{
  FILE *file;
  int i;
  file = fopen ("my.bin","wb+");
  putw (20,file);
  rewind (file);
  i=getw (file);
  fclose(file);
  
  return 0;
}


Messing about with formatted file I/O

#include <stdio.h>
int main()
{
   long num1 = 2345637L;
   long num2 = 3451223L;
   long num3 = 7892234L;
   long num4 = 0L;
   long num5 = 0L;
   long num6 = 0L;
   float fnum = 0.0f;
   int   ival[6] = { 0 };
   int i = 0;
   FILE *pfile = NULL;
   char *filename = "C:\\myfile.txt";
   pfile = fopen(filename, "w");
   if(pfile == NULL){
     printf("Error opening %s for writing. Program terminated.", filename);
   }
   fprintf(pfile, "%6ld%6ld%6ld", num1, num2, num3);
   fclose(pfile);
   pfile = fopen(filename, "r");
   fscanf(pfile, "%6ld%6ld%6ld", &num4, &num5 ,&num6);
   printf("\n %6ld %6ld %6ld", num4, num5, num6);
   rewind(pfile);   /* Go to the beginning of the file */
   fscanf(pfile, "%2d%3d%3d%3d%2d%2d%3f", &ival[0], &ival[1],&ival[2], &ival[3], &ival[4] , &ival[5], &fnum);
   fclose(pfile);                   
   remove(filename);
   for( i = 0 ; i < 6 ; i++ )
     printf("%d\n", ival[i]);
   printf("\nfnum = %f\n", fnum);
}


Open a file and read its content using fgetc

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
  FILE *fp;
  char ch;
  if((fp = fopen(argv[ 1 ],"r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  while((ch = fgetc( fp )) != EOF) {
    printf("%c", ch);
  }
  fclose(fp);
  return 0;
}


Read formatted data from a stream: how to use fscanf

#include <stdio.h>
int main ()
{
  char str[80];
  float f;
  FILE *file;
  file = fopen ("my.txt","w+");
  fprintf (file, "%f %s", 3.14, "PI");
  rewind (file);
  fscanf (file, "%f", &f);
  fscanf (file, "%s", str);
  fclose (file);
  printf (" %f and %s  are added. \n",f,str);
  return 0;
}


Reading strings from a file in reverse order

/*
Beginning C, Third Edition
 By Ivor Horton
 ISBN: 1-59059-253-0
 Published: Apr 2004
 Publisher: apress
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STRING_LENGTH 1000
#define BUFFER_SIZE 50
/* Global variables */
FILE *pInFile = NULL;                   /* File pointer to input file     */
FILE *pOutFile = NULL;                  /* File pointer  to output file   */
char *infilename = "C:\\myfile.txt";    /* Name of the file to be read    */
char *outfilename = "C:\\outfile.txt";  /* Name of the file to be written */
char *buffer = NULL;
size_t buffer_size = BUFFER_SIZE;

void main()
{
  size_t str_length = 0;
  int str_count = 0;
  fpos_t *positions = NULL;
  int i = 0;
  buffer = (char*)malloc(buffer_size);            /* Create initial buffer */
  if((pInFile = fopen(infilename, "r")) == NULL)  /* Open the input file   */
  {
    printf("Error opening %s for reading. Program terminated.", infilename);
    abort();
  }
  /* Find out how many strings there are */
  for(;;)
  {
    fread(&str_length, sizeof(size_t), 1, pInFile);  /* Read the string length */
    if(feof(pInFile))                                /* If it is end of file   */
      break;                                         /* We are finished        */
    /* Check buffer is large enough and increase if necessary */
    if(str_length>buffer_size)
    {
      buffer_size = str_length+1;
      free(buffer);
      buffer = (char*)malloc(buffer_size);
    }
    fread(buffer, str_length, 1, pInFile);   /* Read the string */
    ++str_count;
  }
  printf("\nThere are %d strings in the input file.", str_count);
  /* Now get the position for the beginning of each record in the file */
  /* The buffer is now large enough to hold the longest string         */
  rewind(pInFile);
  positions = (fpos_t*)malloc(str_count*sizeof(fpos_t));  /* Array to store the positions */
  for(i = 0 ; i<str_count ; i++)
  {
    fgetpos(pInFile, positions+i);                    /* Get the positions      */
    fread(&str_length, sizeof(size_t), 1, pInFile);   /* Read the string length */
    fread(buffer, str_length, 1, pInFile);            /* Read the string        */
 }
  /* Open the output file */
  if((pOutFile = fopen(outfilename, "w")) == NULL)
  {
    printf("Error opening %s for reading. Program terminated.", outfilename);
    abort();
  }
  /* Read the records in reverse order from the input file and write to the new file */
  for(i = 0 ; i<str_count ; i++)
  {
    fsetpos(pInFile, positions+str_count-i-1);            /* Set the file position  */
    fread(&str_length, sizeof(size_t), 1, pInFile);       /* Read the string length */
    fwrite(&str_length, sizeof(size_t), 1, pOutFile);     /* Write to new file      */
    fread(buffer, str_length, 1, pInFile);                /* Read the string        */
    fwrite(buffer, str_length, 1, pOutFile);              /* Write to new file      */
  }
  fclose(pInFile);                                        /* Close input file  */
  fclose(pOutFile);                                       /* Close output file */
  printf("\nNew file write complete\n");
  /* List contents of output file */
  if((pOutFile = fopen(outfilename, "r")) == NULL)        /* Open the new file to read it */
  {
    printf("Error opening %s for reading. Program terminated.", outfilename);
    abort();
  }
  printf("\nThe strings in the new file are:");
  for(i = 0 ; i<str_count ; i++)
  {
    fread(&str_length, sizeof(size_t), 1, pOutFile);
    fread(buffer, str_length, 1, pOutFile);
    buffer[str_length] = "\0";
    printf("\n%s", buffer);
  }
  printf("\n");
  fclose(pOutFile);                                    /* Close file */
  /* Free the memory we allocated */
  if(buffer != NULL)
    free(buffer);
  if(positions != NULL)
    free(positions);
 }


Reset the file reader pointer

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
  FILE *fp;
  /* see if filename is specified */
  if(argc != 2) {
    printf("File name missing.\n");
    exit(1);
  }
  if((fp = fopen(argv[1], "r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }
  /* show it once */
  while(!feof(fp))
    putchar(getc(fp));
  rewind(fp);
  /* show it twice */
  while(!feof(fp))
    putchar(getc(fp));
  fclose(fp);
  return 0;
}


Search a set of numbers

/*
Practical C Programming, Third Edition
By Steve Oualline
Third Edition August 1997 
ISBN: 1-56592-306-5
Publisher: O"Reilly
*/
#include <stdio.h>
#define MAX_NUMBERS   1000    /* Max numbers in file */
const char DATA_FILE[] = "numbers.dat";  /* File with numbers */
int data[MAX_NUMBERS];  /* Array of numbers to search */
int max_count;    /* Number of valid elements in data */
int main()
{
    FILE *in_file;  /* Input file */
    int  middle;    /* Middle of our search range */
    int low, high;  /* Upper/lower bound */
    int search;    /* number to search for */
    char line[80];  /* Input line */
    in_file = fopen(DATA_FILE, "r");
    if (in_file == NULL) {
  fprintf(stderr,"Error:Unable to open %s\n", DATA_FILE);
  exit (8);
    }
    /*
     * Read in data 
     */
    max_count = 0;
    while (1) {
  if (fgets(line, sizeof(line),  in_file) == NULL)
      break;
  /* convert number */
  sscanf(line, "%d", &data[max_count]);
  ++max_count;
    }
    while (1) {
  printf("Enter number to search for or -1 to quit:" );
  fgets(line, sizeof(line), stdin);
  sscanf(line, "%d", &search);
  if (search == -1)
      break;
  low = 0;
  high = max_count;
  while (1) {
      if (low >= high) {
    printf("Not found\n");
    break;
      }
      middle = (low + high) / 2;
      if (data[middle] == search) {
    printf("Found at index %d\n", middle);
    break;
      }
      if (data[middle] < search)
    low = middle +1;
      else
    high = middle -1;
  }
   }
   return (0);
}
//File numbers.dat
/*
4
6
14
16
17
18
22
23
26
27
28
29
34
37
40
41
42
46
47
48
51
53
55
57
61
68
69
72
73
74
75
76
77
78
79
82
87
92
93
95
96
99
100
106
107
109
112
113
114
118
120
123
124
125
127
132
135
140
142
145
146
148
150
153
155
158
159
162
165
166
167
172
179
180
183
185
187
191
193
195
196
197
199
201
202
203
209
210
220
222
224
226
228
229
232
234
239
240
242
243
244
246
247
248
250
252
253
254
255
261
264
272
276
279
280
284
288
291
295
296
297
298
304
306
309
310
314
322
325
326
327
329
333
334
341
345
346
349
355
358
360
361
362
363
364
371
372
379
380
382
385
386
387
389
390
391
398
401
404
405
407
409
411
412
421
422
423
428
431
433
435
436
437
438
439
442
444
445
447
448
449
450
451
452
454
456
465
466
467
470
471
472
475
476
478
481
482
484
485
487
490
491
498
501
503
507
509
510
511
512
513
514
517
520
521
523
525
527
528
529
530
535
539
542
548
549
555
556
557
558
559
560
561
568
571
572
574
587
589
590
592
593
598
601
603
604
605
608
609
610
613
614
615
616
619
620
624
628
631
633
636
638
640
643
645
647
648
650
655
656
658
666
667
668
669
670
674
675
678
680
681
689
691
692
693
694
695
697
701
702
704
707
708
710
711
713
714
715
716
718
722
723
726
730
732
736
739
745
746
747
750
753
755
756
757
760
762
763
765
766
769
772
773
776
777
779
781
784
790
794
798
800
808
812
813
815
818
822
823
826
827
830
832
837
838
839
840
842
844
845
847
848
851
853
857
858
859
862
864
874
879
882
883
890
892
895
905
906
907
912
914
918
922
924
927
930
931
938
939
943
945
946
948
949
950
955
958
960
964
966
971
972
976
977
978
979
980
984
986
987
988
990
991
992
*/


Viewing the contents of a file

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define DISPLAY 80
#define PAGE_LENGTH 20
int main(int argc, char *argv[])
{
   char filename[80]="c:\\myfile.txt";
   FILE *pfile;
   unsigned char buffer[DISPLAY/4 - 1];
   int count = 0;
   int lines = 0;
   int i = 0;
   if((pfile = fopen(filename, "rb")) == NULL){
       printf("Sorry, can"t open %s", filename);
       return -1;
   }
   while(!feof(pfile))
   {
     if(count < sizeof buffer) /* If the buffer is not full  */
       printf("%c \n", (unsigned char)fgetc(pfile));
     if(count < sizeof buffer) /* If the buffer is not full  */
       printf("%02X \n", (unsigned char)fgetc(pfile));
   }
   fclose(pfile);
   return 0;
}