Read a line in C and split it

2019-08-29 19:05发布

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: enter image description here

Thanks for any help.

标签: c fread scanf
2条回答
Ridiculous、
2楼-- · 2019-08-29 19:14
  1. You never null-terminate 'str' so the sscanf could read off the end.

  2. You need to pass to sscanf the addresses of the output variables, not the values. (Eg. &i instead of i).

  3. If you enable compiler warnings (-Wall with gcc), your compiler will warn you about the second point, at least.

查看更多
混吃等死
3楼-- · 2019-08-29 19:20

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:

FILE *fp;
int i,j;
char str[9] = { 0 };
char valor;
if(!(fp = fopen("miniflota_g.dat","rb"))){
    printf("Error opening file.");
    getch();
    return;
}
while(fread(str,sizeof(str)-1,1,fp) == 1){
    sscanf(str,"%d %d %c",&i,&j,&valor);
    printf("%d %d %c",i,j,valor);
}
fclose(fp);
查看更多
登录 后发表回答