I got a problem trying to split 'str' in 2 int vars and 1 char var. Here is a code:
FILE *fp;
int i,j;
char str[8];
char valor;
if(!(fp = fopen("miniflota_g.dat","rb"))){
printf("Error opening file.");
getch();
return;
}
while(fread(str,sizeof(str),1,fp) == 1){
sscanf(str,"%d %d %c",i,j,valor);
printf("%d %d %c",i,j,valor);
}
fclose(fp);
And this is an error:
Thanks for any help.
You never null-terminate 'str' so the sscanf could read off the end.
You need to pass to sscanf the addresses of the output variables, not the values. (Eg.
&i
instead ofi
).If you enable compiler warnings (-Wall with gcc), your compiler will warn you about the second point, at least.
sscanf() works only on standard C 0-terminated strings. fread() does not append a 0 to what it reads. If you want to read 8 bytes and use sscanf() you need to 0-terminate the data first. So your array needs to be at least 9 bytes big, so you can append a 0 to the data.
Also you need to pass the variable addresses to it, so it can write to them.
So it should look more like this: