读取dat文件并向数组添加数字

时间:2013-04-02 06:34:15

标签: c arrays file

我的程序要求我读取带有数字列表的dat文件。我的目标是获取每个数字并将它们添加到数组中。该文件以这种格式包含大约100个数字:

  

1

     

2

     

3

(造型有点遗憾; [)

到目前为止我已经

int main()
{
    double prices[1000];
    int count,price;

    FILE *file;
    file = fopen("price.dat","r");
    if(file == NULL)
    {
        printf("Error: can't open file to read\n");
    }
    else
    {   
        printf("File prices.dat opened successfully to read\n");
    }
    if (file){
        while (fscanf(file, "%d", &price)!= NULL){
            count++;
            prices[count]=price;
        }
    }
    fclose(file);
}

问题是它会继续连续添加最后一个数字。有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

您的代码中存在多个问题。仅举几例:

  • fscanf不返回指针,因此您不应将其与NULL进行比较。所有scanf函数都返回一个整数,可以是正数,零或负数。
  • 您没有初始化count,因此它将包含一个看似随机的值。
  • 数组的索引从零开始,因此在分配之前不应增加数组索引count

不想停止的实际问题是因为第一点。

答案 1 :(得分:1)

#include <stdio.h>
#include <string.h>

#define PRICES_LIST_MAX      1000
#define PRICES_FILE          "price.dat"

int main()
{
    double prices[PRICES_LIST_MAX];
    int count = 0;
    int i = 0;

    FILE *file;
    file = fopen(PRICES_FILE,"r");
    if(!file)
    {
        perror("Error opening file");
        return -1;
    }

    memset(prices, 0, sizeof(prices));
    while (!feof(file)               /* Check for the end of file*/
        &&(count < PRICES_LIST_MAX)) /* To avoid memory corruption */
    {
        fscanf(file, "%lf", &(prices[count++]));
    }
    fclose(file);

    /* Print the list */
    printf("Prices count: %d\n", count);
    for(i = 0; i < count; i++)
    {
        printf("Prices[%d] = %lf\n", i, prices[i]);
        }

        return 0;
}