无法用C中的文本文件中的数据填充数组

时间:2015-01-11 16:17:14

标签: c arrays

我有一个名为proj3input.dat的数据文件,它有10000个条目,我必须用它来填充数组。我无法将文件中的数据导入阵列。这段代码(抱歉丑陋的格式化,它完全改变了,我粘贴到stackoverflow)当前打印一个满0的数组,我无法看到我的错误在哪里。数据点都是小数,而不是整数,现在我只需要获取数据点来填充我的数组[10000]。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define MAX_FILE_NAME 100

int main(int argc, char *argv[])
{
  FILE *proj3input, *output;
  int i, count = 0, max_window, window_size, p, m, q, x;
  int *num_windows;
  double time[10000], data[10000], data_mean, data_sum;
  char filename[MAX_FILE_NAME];
  char c;

  /* Open files */
  proj3input = fopen("proj3input.txt", "r");
  output = fopen("output.dat", "w"); /* prototype any functions! */

  /*Verify file*/
  if (proj3input == (FILE *)NULL) {
    printf("**********ERROR**********\n");
    printf("* Cannot open required  *\n");
    printf("*  file. Please check   *\n");
    printf("*    your directory     *\n");
    printf("**********ERROR**********\n");
    exit(EXIT_FAILURE);
  }

  for (c = getc(proj3input); c != EOF; c = getc(proj3input)) {
    if (c == '\n') {
      count = count + 1;
    }
  }
  printf("The file has %d lines \n", count);
  max_window = count;
  printf("Please enter the size of the window you require.\n");
  printf("This must be an integer greater than 1 and less than %d\n",
         max_window);
  scanf("%d", &window_size);

  /* If validation failed ... */
  /*if(!validInput)
  {
     printf(" ERROR: No input detected. Please input a positive integer. \n");
     return(EXIT_FAILURE);
     }*/

  /* Here we check that we have a valid window size*/
  if (window_size == 0) {

    printf("**********ERROR**********\n");
    printf("*  Input value must be  *\n");
    printf("*  nonzero. Please run  *\n");
    printf("*  again with non zero  *\n");
    printf("*        input          *\n");
    printf("**********ERROR**********\n");
  }

  if (num_windows == NULL) {
    printf("Memory allocation failure. Exiting...\n");
    return (EXIT_FAILURE);
  }

  for (i = 0; i <= 10000; i++) {
    fscanf(proj3input, "%lf", &data[i]);
  }

  /* Close the file */
  fclose(proj3input);

  for (x = 0; x < 10; x++) {
    printf("%lf\n", data[x]);
  }

  return 0;
}

1 个答案:

答案 0 :(得分:3)

用于计算行数的循环读取整个文件:

for(c= getc(proj3input); c != EOF; c = getc(proj3input)){
    if(c == '\n'){
        count = count + 1; 
        }
}

因此,当您再次阅读时,您已经在文件的末尾,无法进一步阅读。您需要在初始行计数后添加rewind来电:

rewind(proj3input);