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, ...); 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]