I have actually a small problem with file i/o and finding the right algorithm to read the data correctly. The problem is, that the “header” could look a little bit different from each file.
For example:
File 1.
500 500
100
Binary
File 2.
500
d500
100
Binary
File 3.
500
500
100
Binary
File 4.
500
500 100
Binary
…
I’m interested to get the 3 numeric values. I tried it with fgets and scanf and also with fscanf… and so one.
But I find at every try a way, where I’m not able to get the values.
Dose someone have some ideas, who I could get the values in every case?
Edit
/* Jump over the identification and comment strings. */
fseek(in, 3, SEEK_SET);
do
{
fgets(line, PREAMBLE, in);
} while(strncmp(line, "#", 1) == 0);
/* Save the information in the structer. */
sscanf(line, "%u %u", &imginf.width, &imginf.height);
fgets(line, PREAMBLE, in);
sscanf(line, "%u", &imginf.depth);
return imginf;
This works for example:
File
500 500
100
Binary
Solution
Her is the interesting part of the code. Now I think I get every value. Maybe the code looks a little bit smelly, I haven not made sure that the code is clean.
while (a[2] == 0 ){
fgets(line, 255, in);
i = 0;
while (line[i] != '\0') {
if ((line[i] < '0') || (line[i] > '9')) {
i++;
}
else {
while ((line[i] >= '0') && (line[i] <= '9')) {
buffer[j] = line[i];
j++;
i++;
}
j = 0;
a[k] = atoi(buffer);
printf("%d\n", a[k]);
strcpy(buffer, "");
k++;
}
}
}
Greetz
Read character-by-character and parse the input yourself.
Something like