The problem is in line 7: int ret=3, x, y;
if I declare the y first (like the line 8) the result will be different
on my computer right now is printing only the Y values, with this change in the declaration goes to print only the values of X
gcc -g -o open_file_test open_file_test.c;
./pen_file_test input
#include <stdio.h>
#include <stdlib.h>
int worldsize = 0;
int main(int argc, char const *argv[]){
int ret=3, x, y;
//int ret=3, y, x;
char chr;
int teste;
FILE * inputFile;
inputFile = fopen(argv[1],"r");
teste = fscanf(inputFile,"%d", &worldsize);
printf("Tamanho: %d\n", worldsize);
while(1){
ret=fscanf(inputFile,"%d %d %s\n", &x, &y, &chr);
if(ret != 3)
break;
printf("x: %d y: %d\n", x, y);
}
printf("End File :D\n");
return 0;
}
10 1 0 w 2 1 s 6 9 w 3 7 w 5 0 s 1 5 t 1 5 t 7 5 t 9 7 t 9 3 t 0 0 i
Tamanho: 10 x: 0 y: 0 x: 0 y: 1 x: 0 y: 9 x: 0 y: 7 x: 0 y: 0 x: 0 y: 5 x: 0 y: 5 x: 0 y: 5 x: 0 y: 7 x: 0 y: 3 x: 0 y: 0 End File :D
On my computer only read the Y, and the same code on my colleague computer only reads X, and in another friend's computer works fine (read the X and Y), can somebody explain the reason?
You have undefined behaviour in your code here:
fscanf(inputFile,"%d %d %s\n", &x, &y, &chr);
Reading a string into chr
which is a single char
variable. Even if the string contains a single character, a null-terminator will be written after it. This may well be spilling into your integers on the stack.
If you want a single char, then use %c
:
fscanf(inputFile,"%d %d %c\n", &x, &y, &chr);
If you prefer a string, then make chr
a char
array large enough to hold any potential string (plus a null terminator). Alternatively, use fgets
to read a line at a time and then parse the values out later.
On this line:
ret=fscanf(inputFile,"%d %d %s\n", &x, &y, &chr);
Your fscanf
format has %s
, which means "String" (several characters, ending with a NULL-terminator) , but the matching variable for the data, chr
is only a single character, and cannot handle multiple characters.
To fix it, I recommend using formatter %c
(which means a single character) instead of %s
.
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.