简体   繁体   English

如何在 c 语言中使用 fscanf 从文件中读取数据

[英]How to read data from file with fscanf in c-language

I want to import numbers (40000 in total, space-separated) (format: 2.000000000000000000e+02) with "fscanf" and put it in a 1D-Array.我想用“fscanf”导入数字(总共40000,以空格分隔)(格式:2.000000000000000000e+02)并将其放入一维数组中。 I tried a lot of things, but the numbers I am getting are strange.我尝试了很多东西,但我得到的数字很奇怪。

What I've got until now:到目前为止我所拥有的:

int main() {
        FILE* pixel = fopen("/Users/xy/sample.txt", "r");
        float arr[40000];
        fscanf(pixel,"%f", arr);
   
        for(int i = 0; i<40000; i++)
            printf("%f", arr[i]);
}

I hope somebody can help me, I am a beginner;-) Thank you very much!!我希望有人可以帮助我,我是初学者;-) 非常感谢!!

Instead of:代替:

fscanf(pixel,"%f", arr);

which is the exact equivalent of this and which read only one single value:这与此完全等效,并且仅读取一个值:

fscanf(pixel,"%f", &arr[0]);

you want this:你要这个:

for(int i = 0; i<40000; i++)
   fscanf(pixel,"%f", &arr[i]);

Complete code:完整代码:

#include <stdio.h>
#include <stdlib.h>

int main() {
  FILE* pixel = fopen("/Users/xy/sample.txt", "r");
  if (pixel == NULL)   // check if file could be opened
  {
    printf("Can't open file");
    exit(1);
  }

  float arr[40000];
  int nbofvaluesread = 0;

  for(int i = 0; i < 40000; i++)  // read 40000 values
  {
     if (fscanf(pixel,"%f", &arr[i]) != 1)
       break;     // stop loop if nothing could be read or because there
                  // are less than 40000 values in the file, or some 
                  // other rubbish is in the file
     nbofvaluesread++;
  } 
  
  for(int i = 0; i < nbofvaluesread ; i++)
     printf("%f", arr[i]);

  fclose(pixel);  // don't forget to close the file
}

Disclaimer: this is untested code, but it should give you an idea of what you did wrong.免责声明:这是未经测试的代码,但它应该让您了解您做错了什么。

You need to call fscanf() in a loop.您需要循环调用fscanf() You're just reading one number.你只是在读一个数字。

int main() {
    FILE* pixel = fopen("/Users/xy/sample.txt", "r");
    if (!pixel) {
        printf("Unable to open file\n");
        exit(1);
    }

    float arr[40000];
    for (int i = 0; i < 40000; i++) {
        fscanf(pixel, "%f", &arr[i]);
    }

    for(int i = 0; i<40000; i++) {
        printf("%f", arr[i]);
    }
    printf("\n");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM