01: // ungetc() usage
02: #include<stdio.h>
03: #include<stdlib.h>
04: #include<ctype.h>
05: 
06: int main(int argc, char **argv){
07: 
08:   FILE *fp = fopen("files/numeri.txt", "r");
09: 
10:   if(!fp)
11:   {
12:     perror("");
13:     exit(EXIT_FAILURE);
14:   }
15: 
16:   // in the input file we have "numbers" mixed inside a text, how we can extract them?
17:   // the idea is to read the file char by char using fgetc(), once a digit is found we can then read
18:   // the number using fscanf() as usual
19: 
20:   char c;     // to be used to read the file byte by byte
21:   int n;      // to be used to read a number from a file
22:   while( (c = fgetc(fp)) != EOF)
23:   {
24:     if(!isdigit(c)) // if we read a symbol that is not a digit we can go on
25:       continue; 
26: 
27:     // if we arrive here, we read the first digit of a number.
28:     // In order to read the number we can use fscanf().
29:     // Problem: we already "consumed" the first digit, namely fscanf() would read only a part of the number...
30:     // Solution: put back the char to the stream using ungetc()
31:     ungetc(c, fp);
32: 
33:     // after the ungetc() we can read the WHOLE number using formatted input
34:     fscanf(fp, "%d", &n);
35: 
36:     printf("I read a number: %d\n", n);
37:   }
38:   fclose(fp);
39: 
40:   return 0;
41: }
42: 
43: 


Se avete commenti o osservaƶioni su questa pagina
mandate un messaggio di posta elettronica a bertoƶƶi@ce.unipr.it