如何将名称文件读入数组

时间:2014-06-20 04:38:07

标签: c string scanf

我需要帮助读取名称列表并将它们存储到字符串中。我已经为字符串分配了内存,我只需要帮助实际读取并存储它们。这是我已经编写的信息和代码。我只需要insert_data函数的帮助。

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

#define MAX_STRING_LEN 25 

void insert_data(char **strings, const char *filename, int size); 
void allocate(char ***strings, int size); 

int main(int argc, char* argv[]){ 

   if(argc != 4){ 
      printf("Wrong number of args"); 
   } 

   char **pointer; 
   int size = atoi(argv[1]); 
   allocate(&pointer, size); 
   insert_data(pointer, argv[2], size);
} 



void allocate(char ***strings, int size){ 

   int i; 
   *strings = (char**) malloc(sizeof(char**) * size); 

    for( i = 0; i < size; i++) 
    { 
        (*strings)[i] = malloc(sizeof(char) * MAX_STRING_LEN); 
    } 
} 

这是我需要帮助的功能:

void insert_data(char **strings, const char *filename, int size){

    FILE *input;
    input = fopen(filename, "r");

    int i;
    for (i = 0; i < size; i++){

    fscanf(input,"%s", (*strings)[i]);

    }

    fclose(input);
}

以下是我正在阅读的列表:

matt 
susan 
mark 
david 
aden 
phil 
erik 
john 
caden 
mycah 

1 个答案:

答案 0 :(得分:0)

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

#define MAX_STRING_LEN 25 
#define _S(x) #x
#define S(x) _S(x)

void insert_data(char **strings, const char *filename, int size); 
void allocate(char ***strings, int size); 

int main(int argc, char* argv[]){ 

    if(argc != 3){ 
        printf("Wrong number of args\n");
        printf("Usage:%s size filename\n", argv[0] ? argv[0] : "prog");
        exit(-1);
    } 

    char **pointer; 
    int size = atoi(argv[1]); 
    allocate(&pointer, size); 
    insert_data(pointer, argv[2], size);
    int i;
    for(i=0;i<size;++i){
        printf("%s\n", pointer[i]);
        free(pointer[i]);
    }
    free(pointer);
    return 0;
}

void allocate(char ***strings, int size){ 
    int i; 

    *strings = malloc(sizeof(char*) * size); 
    for( i = 0; i < size; i++) {
        (*strings)[i] = malloc(sizeof(char) * (MAX_STRING_LEN+1)); 
    }
} 

void insert_data(char **strings, const char *filename, int size){
    FILE *input= fopen(filename, "r");
    int i;
    for (i = 0; i < size; i++){
        fscanf(input,"%" S(MAX_STRING_LEN)  "s", strings[i]);
    }
    fclose(input);
}