c - 用文本文件中的数据填充数组

标签 c

我有一个包含双数据的 .txt 文件。每个都在一个新的行中。 我即将从文件中读取两次 - 一次用于计算文件有多少个数字,第二次 - 用数据填充数组。所以我这样做了:

#include <stdio.h>

char name[30];
scanf ("%s", name);

FILE *file = fopen (name, "r");
if (!file) 
{
    printf ("Cannot read from file %s!\n", name);
    return 1;
}

double results;
int size = 0;
while ( fscanf (plik, "%lf", &results) != EOF)
{
    size++;
}
//and here I have how many numbers is in the file

double numbers[size]; 
for (int i=0; i<size; i++)
{
    fscanf (plik, "%lf\n", &numbers[i]);

}   
for(int i = 0; i < size; i++)
{
    printf("%lf\n" , numbers[i]);
}

但它不起作用 - 结果只有 0.000000,总计 6510(这么多)。谁能帮忙解决这个问题吗?

最佳答案

正如 Chris 所指出的,当您在第一遍中读取文件时,fscanf 会移动文件指针。所以你在第二遍中没有读到任何内容。我假设所有代码都在 main 函数中,而 plik 只是从 file 复制的另一个标识符。使用 fseek(file, 0, SEEK_SET) 将文件指针重置为文件开头似乎可以解决我的问题:

#include <stdio.h>

int main() {
  char name[30];
  scanf ("%s", name);

  FILE *file = fopen (name, "r");
  if (!file) 
    {
      printf ("Cannot read from file %s!\n", name);
      return 1;
    }

  double results;
  int size = 0;
  FILE *pFilePtr = file;
  printf("file = %p\n", file);
  while ( fscanf (pFilePtr, "%lf", &results) != EOF) 
      size++;
  printf("size : %d\n", size);

  double numbers[size]; 
  fseek(file, 0, SEEK_SET);
  FILE *plik = file;
  for (int i=0; i<size; i++)
      fscanf (plik, "%lf", &numbers[i]);
  for(int i = 0; i < size; i++)
      printf("%lf\n" , numbers[i]);
  return 0;
}

我运行它假设这个文件输入:

~/Documents/src : $ cat testFile.txt 
1.2334 2.223 3.34 4.21 5.34 6.23
~/Documents/src : $ g++ testFillArr.c
~/Documents/src : $ ./a.out 
testFile.txt    
file = 0x559494bdd420
size : 6
1.233400
2.223000
3.340000
4.210000
5.340000
6.230000

关于c - 用文本文件中的数据填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46117781/

相关文章:

C linux shmget 参数无效

CodeVision AVR 发送和接收 USART 数据

c++ - 链接 boolean 值给出与预期相反的结果

c++ - 寻找与另一个相反的 vector ?

C 数据结构错误

c - struct_ 前缀与无前缀

c - 函数调用的测试条件和执行大致相同的简单测试

c - 当 main() 函数不返回零时会发生什么

c - 将变量从 .bss 移动到 .data 是否危险?

python - 如何从 C 到 Python 编写这个 for 循环?