C Lecture 5
[Previous Lecture]
[Lecture Index]
[Next Lecture]
total.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
int
main()
{
FILE *fp;
char filename[1024];
char *p;
int total;
int num;
int rval;
while (1) {
printf("\n(enter blank line to exit)\n");
printf("Enter filename: ");
fflush(stdout);
if (!fgets(filename, sizeof(filename), stdin))
break;
p = strchr(filename, '\n');
if (p)
*p = '\0';
if (strlen(filename) == 0)
break;
fp = fopen(filename, "r");
if (fp == 0) {
fprintf(stderr, "Unable to open %s - %s\n",
filename, strerror(errno));
continue;
}
for (total = 0; ; total += num) {
rval = fscanf(fp, "%d", &num);
if (rval == EOF)
break;
if (rval == 0) {
fprintf(stderr, "Error in input: can't read number\n");
break;
}
}
fclose(fp);
printf("Total of all read numbers: %d\n", total);
}
return 0;
}
scanf()
int scanf(char *fmt, ...);
- used for reading formatted input from stdin
- design similar to that of printf()
- first argument is the format string
- remaining arguments are the addresses of the
variables to be read into
- returns number variables that were successfully scanned
(number of matching % sequences)
- non-% characters in format must match input
(spaces match any amount of white space)
- % sequences in format string:
- %d: read a decimal integer
- %c: read a single character
- %s: read a sequence of characters (ended by a white space)
- %f: read a floating point number
- %lf: read a double floating point number
- %%: expect a % character
except for %% and %c, any amount of white space is skipped
before a % sequence
Examples:
char buf[1024];
float num;
char c;
scanf("%c%s =%f", &c, buf, &num);
printf("c is %c, buf is %s, num is %f\n",
c, buf, num);
[Previous Lecture]
[Lecture Index]
[Next Lecture]