Let me go over your code, and show you exactly what is wrong.
Originally Posted by
csharp100
Code:
printf("Cannot open file for reading");
You forgot the newline at end of the line. Also, it would be better to write to standard error. That way, if the user redirected the expected output to a file, they will still see the error messages. So:
Code:
fprintf(stderr, "Cannot open file for reading.\n");
That was not really an issue, but it is so useful in practice I thought I'd point it out anyway.
The real problems are in the following:
Originally Posted by
csharp100
Code:
fgets(buf, sizeof(buf), fp);
for (i = 0; i < SIZE; i++){
sscanf(buf, "%d", &array[i]);
}
First, you are reading just one line, then parsing it again and again in the loop.
Second, you don't check the fgets() return value; it may return NULL if it cannot read the line.
Third, you don't check the sscanf() return value to see if it did the conversion or not.
I'd recommend you add a new variable, say char *line;, and moved the fgets() inside the loop:
Code:
line = fgets(buf, sizeof buf, fp);
if (!line) {
fprintf(stderr, "Cannot read line %d.\n", i + 1);
exit(EXIT_FAILURE);
}
Similarly, to check that sscanf() really did do a conversion, check its return value -- the number of conversions you require from it:
Code:
if (sscanf(line, "%d", &array[i]) < 1) {
fprintf(stderr, "Line %d does not start with an integer.\n", i + 1);
exit(EXIT_FAILURE);
}
If you want to be thorough, you could also check the fclose() return value. You really should check it whenever you write to a file. It will return zero if there were no problems, and nonzero (EOF) if there is a problem. I'd recommend
Code:
if (fclose(fp)) {
fprintf(stderr, "Error closing the file.\n");
exit(EXIT_FAILURE);
}