C语言 读取txt文件中的数字列表并存储到C中的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14802470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:18:52  来源:igfitidea点击:

Read list of numbers in txt file and store to array in C

carrays

提问by TrialName

I have a list of integers, one number per line and would like to store each of these numbers in an integer array to use later in the program.

我有一个整数列表,每行一个数字,并希望将这些数字中的每一个存储在一个整数数组中,以便稍后在程序中使用。

For example in java you would do something like this:

例如在 Java 中,你会做这样的事情:

FileReader file = new FileReader("Integers.txt");
int[] integers = new int [100];
int i=0;
while(input.hasNext())
{
   integers[i] = input.nextInt();
   i++;
}
input.close();

How would this be done in C?

这将如何在 C 中完成?

回答by shanet

Give this a go. You'll be much better off if you read the man pages for each of these functions (fopen(), scanf(), fclose()) and how to allocate arrays in C. You should also add error checking to this. For example, what happens if Integers.txt does not exist or you don't have permissions to read from it? What about if the text file contains more than 100 numbers?

试试这个。如果您阅读这些函数(fopen()、scanf()、fclose())中的每一个的手册页以及如何在 C 中分配数组,您的情况会好得多。您还应该为此添加错误检查。例如,如果 Integers.txt 不存在或者您没有读取它的权限会发生什么?如果文本文件包含超过 100 个数字怎么办?

    FILE *file = fopen("Integers.txt", "r");
    int integers[100];

    int i=0;
    int num;
    while(fscanf(file, "%d", &num) > 0) {
        integers[i] = num;
        i++;
    }
    fclose(file);

回答by mikyra

#include <stdio.h>

int main (int argc, char *argv[]) {
  FILE *fp;
  int integers[100];
  int value;
  int i = -1; /* EDIT have i start at -1 :) */

  if ((fp = fopen ("Integers.txt", "r")) == NULL)
    return 1;

  while (!feof (fp) && fscanf (fp, "%d", &value) && i++ < 100 )
    integers[i] = value;

  fclose (fp);

  return 0;
}