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

时间:2022-08-26 11:59:17

I need to read in a file, each line of the file has one string on it (max 50 char long) and i need to store each line into an array of pointers. So if the file reads:

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

1234
abcd
5667
...

Then the array (called functions) would be *functions[0] = 1234, *functions[1]= abcd and so on...

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

I've tried a few things now and i can't quite seem to get it to work. This is the start of my code, or at least the parts pertaining to my confusion:

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

#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");

I've tried a few things but I can't manage to make *functions store the values properly. Can someone help me out? :)

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

1 个解决方案

#1


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]);
}
}

#1


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]);
}
}