Lab overview
Lab 01
Lab 02
Lab 03
Lab 04
Lab 05
Lab 06
Lab 07
Lab 08
Lab 09
Lab 10
Lab 11
Lab 12
Lab 13
Review

[Course home page]

CSC 209 lab 10 solutions, week of 19 July 2022

Question 7:

Problem:
Read a number from the file "foo", or return −1 if the file doesn't exist or doesn't begin with a number.

Code:

int foonumber()
{
    int x;
    FILE *fp = fopen("foo", "r");
    if (fp == NULL)
        perror("foo");
    if (fscanf(fp, "%d", &x) == 0)
        return(-1);
    return(x);
}

Solution:

int foonumber()
{
    int x;
    FILE *fp = fopen("foo", "r");
    if (fp == NULL)
	return(-1);
    if (fscanf(fp, "%d", &x) != 1)
        x = -1;
    fclose(fp);
    return(x);
}

Problems fixed above:

"It's impossible to foresee the consequences of being clever."
-- Christopher Strachey


[press 'back' in your web browser to return to the problems]