#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
read_file(const char *fname)
{
FILE *f;
char line[1024];
int lineno, int1, int2, nbytes;
double dbl;
if ((f = fopen(fname, "r")) == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
for (lineno = 1; fgets(line, sizeof line, f) != NULL; lineno++) {
int fields = sscanf(line, " %d %d %lg %n", &int1, &int2, &dbl, &nbytes);
if (fields != 3 || (size_t) nbytes != strlen(line)) {
fprintf(stderr, "E: %s:%d: badly formatted data\n", fname, lineno);
exit(EXIT_FAILURE);
}
/* do something with the numbers */
fprintf(stdout, "number one is %d, number two is %d, number three is %f\n", int1, int2, dbl);
}
if (fclose(f) == EOF) {
perror("fclose");
exit(EXIT_FAILURE);
}
}
int main(void)
{
read_file("filename.txt");
return 0;
}
Some notes on the code:
- The
fscanf
function is quite difficult to use. I had to experiment a while until I got it right. The space characters between the %d
and %lg
are necessary so that any white-space between the numbers is skipped. This is especially important at the end of the line, where the newline character must be read.
- Most of the code is concerned with checking errors thoroughly. Almost every return value of a function call is checked whether it succeeded or not. In addition, the number of fields and the number of characters that have been read are compared to the expected values.
- The format strings for
fscanf
and fprintf
differ in subtle details. Be sure to read the documentation for them.
- I used the combination of
fgets
to read one line at a time and sscanf
to parse the fields. I did this because it seemed impossible to me to match a single \n
using fscanf
.
- I used the GNU C Compiler with the standard warning flags
-Wall -Wextra
. This helped to avoid some easy mistakes.
Update: I forgot to check that each invocation of fgets
reads exactly one line. There might be lines that are too long to fit into the buffer. One should check that the line always ends with \n
.