不能用的fscanf正确读取 [英] Can't read properly with fscanf

查看:299
本文介绍了不能用的fscanf正确读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的困难。我试图读取该文件。

  3
1 2 3
2
4 5

这是一个人的数字是数组的大小(3和2)。而下面的数字是数组。
因此, 3的大小(1,2,3) 2的大小(4,5)

我写了一篇关于℃,code读取数字,并将它们存储在数组中使用的malloc()

这是我的code:

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;
主要(){
    INT I = 0,J,*尺寸,*载体;    大小=(INT *)malloc的(的sizeof(INT));
    矢量=(INT *)malloc的(的sizeof(INT));    FILE *文件;
    文件= FOPEN(FILE.DAT,RT);    如果(文件== NULL){
        的printf(退出...);
        出口(1);
    }
    其他{
        做{
            的fscanf(文件%d个,&安培;大小[I]);
            为(J = 0; J< =大小[I]; J ++){
                的fscanf(文件%D,和矢量[J]);
            }
            我++;        }而(的feof(文件)== 0);
    }
    FCLOSE(文件);返回0;
}

时的正确读取该文件,但如果我的printf号码我得到:

  3

2
3
4
2


解决方案

两件事情在这里提到。


  1. 您已经通过分配的内存只有一个变量的malloc(),但您尝试访问超出分配的内存中的做...而循环。您需要的realloc(),在需要时。


  2. 请参见为什么,而(!的feof(文件))永远是错的?


I have the following difficulties. I'm trying to read this file.

3
1 2 3
2
4 5

The numbers that are alone are the size of the array (3 and 2). And the following numbers are the array. So 3 is the size of (1,2,3) and 2 is the size of (4,5).

I wrote a code on C to read that numbers and store them in arrays that use malloc().

This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main(){
    int i=0, j, *size, *vector;

    size=(int*)malloc(sizeof(int));
    vector=(int*)malloc(sizeof(int));

    FILE *file;
    file=fopen("file.dat", "rt");

    if (file==NULL){
        printf("Exit ...");
        exit(1);
    }
    else {
        do{
            fscanf(file,"%d",&size[i]);
            for(j=0;j<=size[i];j++){
                fscanf(file,"%d",&vector[j]);
            }
            i++;

        }while(feof(file)==0);
    }
    fclose(file);

return 0;
}

Is reading the file properly but if I printf the numbers I get:

3
5
2
3
4
2

解决方案

Two things to mention here.

  1. You have allocated memory for only one variable through malloc(), but you try to access beyond the allocated memory in the do...while loop. You need to realloc(), as and when required.

  2. Please see Why is "while ( !feof (file) )" always wrong?

这篇关于不能用的fscanf正确读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆