需要帮助将文件内容扫描到指针数组中

时间:2011-05-16 07:17:31

标签: c arrays pointers input

我需要读取一个文件,文件的每一行都有一个字符串(最多50个字符长),我需要将每一行存储到一个指针数组中。所以如果文件是:

1234
abcd
5667
...

然后数组(称为函数)将是* functions [0] = 1234,* functions [1] = abcd等等......

我现在尝试了一些东西,但我似乎无法让它发挥作用。这是我的代码的开始,或者至少是与我的混淆有关的部分:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 201            /* 200 is th emax number of lines in the file*/
#define MAX_FUNCTION_LENGTH 51    /* each line is at ax 50 characters long

main() {
    char func[MAX_FUNCTION_LENGTH]
    char * functions[MAX_SIZE]      /* this is my ragged array*/    
    FILE * inf;
    inf =fopen("list.txt", "r");

我尝试过一些东西,但我无法让*函数正确存储值。有人可以帮我吗? :)

1 个答案:

答案 0 :(得分:1)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 201

int main( int argc, char **argv ) {
    FILE *fp = fopen ( "D:\\personal\\input.txt","r");
    if ( !fp )
        exit ( -1 );
    char line [50];
    char *functions[MAX_SIZE];
    int index = 0;
    while (!feof(fp)) {
        fgets (line , 50 , fp);
        functions[index++] = strdup (line);
    }
    fclose ( fp );
    for ( int i = 0; i < index; i++) {
        printf ( "[%d] -> [%s]\n", i, functions[i]);
    }
    for ( int i = 0; i < index; i++) {
           free ( functions[i]);
}
}