Adak: Perhaps it might be better to abort in all error cases, just like the code does if the file cannot be opened? And maybe add some comments, too?
Say,
Code:
/* Verify the file was opened. */
if (!fp) {
printf("Error opening data.txt file!\n");
return 1;
}
/* Read the number count from the file. */
if (fscanf(fp, "%d", &numdigits) != 1) {
printf("Cannot read the number count from data.txt!\n");
return 1;
}
if (numdigits < 1) {
printf("The number count in data.txt was too small!\n");
return 1;
}
/* Allocate memory for numdigits integer numbers. */
digits = malloc(numdigits * sizeof *digits);
if (!digits) {
printf("Out of memory (asked for %d numbers).\n");
return 1;
}
/* Read numdigits integers into the allocated array. */
for (i = 0; i < numdigits; i++) {
if (fscanf(fp, "%d", &digits[i]) != 1) {
printf("Error reading number %d of %d from data.txt!\n", i + 1, numdigits);
return 1;
}
/* Print the read number to standard output. */
printf("%d\n", digits[i]);
}
Or is this actually going too far? It is almost all the necessary code..