Im trying to read a file with this format:
05874121 A 7
07894544 C 3
05655454 B 5
05879544 B 6
05763465 C 2
and assign each 'word' to different variables (dni, model, trash)
This code is running on Linux, and I use CLion for debugging.
char *path = "file.txt";
FILE *f;
int result;
char dni[9], model[1], trash[100];
f = fopen(path, "r");
do {
result = fscanf(f, "%s %s %s", dni, model, trash);
printf("DNI: %s\n", dni);
}
while( result > 0);
fclose(f);
This should print the first column values, but when I execute the program, the output is just: "DNI: " "DNI: " "DNI: " ... and so on.
While debugging, I realized that "dni" store correctly all the numbers (as chars), but the very first element, dni[0], is always: 0 '/000' like if it was the end of the string.
I dont know why is happening this.
I did 2 corrections in your code:
#include <stdio.h>
int main (int argc, char ** argv) {
char *path = "file.txt";
FILE *f;
int result;
char dni[9], model[2], trash[100];
f = fopen(path, "r");
while(1) {
result = fscanf(f, "%s %s %s", dni, model, trash);
if (result < 1) break;
printf("DNI: %s model %s trash %s\n", dni, model, trash);
}
fclose(f);
return 0;
}
First, the variable model[2] must have an extra character for the end of the string.
Then, the line "if (result <1) break;".
Probably, the error was the model[1] with only one character. The \\ 000 in dni can be the end of the model string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.