从C文本中将文本文件中的数字数组读入数组

时间:2016-03-02 06:20:02

标签: c

这是写入文本文件ex的内容。 “123.txt”:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 

如何将这些数字拉入阵列?

我的想法:

  1. 打开文件(当然)

  2. 使用某种形式的fscanf

  3. 将fscanf置于循环下,并在循环进行时为新数组分配数字

  4. 关闭文件

  5. 非常感谢任何关于如何做到这一点的想法。谢谢你的时间。

    编辑1:

    注意我正在考虑在这个问题上严格学习目的的效率问题。此外,隐含了错误检测,但不包括在内。

    int* load( const char* filename ) {
         int i;
         len = 100; // How to find len of array?
         array[len];
         FILE* fp = fopen( filename, "r" )
    
         while( !feof(fp) ) {
            fscanf(fp,"%d, ",&array[i]);
                i++;
            }
            fclose(f1);
         return array;
    

    循环中的代码不会结束。

3 个答案:

答案 0 :(得分:0)

scanf函数通常很慢。我会用fread和strtok。

stat file get size
allocate buffer
fread to buffer
while not end of buffer
strtok
array[index] = strtoul(buf, 0, 10)
loop

在手册页链接上strtok的好例子 http://man7.org/linux/man-pages/man3/strtok.3.html

答案 1 :(得分:-1)

只是一般方式。你可以根据需要改变它。

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

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

答案 2 :(得分:-1)

尝试将文件重定向到stdin。一个弱代码,仍然有效。:p

#include<stdio.h>

main()
{
freopen("fileName","r",stdin);
char arr[200];
int result[10],i=0;
do
{
    scanf("%s",arr);
    if(arr[0]!='[' && arr[0]!=']')
    result[i++]=atoi(arr);
}while(arr[0]!=']');

}