2012-06-29 61 views
0

我想从一个文件读取一个字符串列表到一个数组。 的文件时,它看起来像这样从一个文件读取到一个字符数组

ItemOne 
ItemTwo 
ItemThree etc. 

我声明数组作为:

char** array; 

和文件为:

FILE *read; 

这是我想出了:

{ 
    i = 0; 
    printf("Type in the name of the file\n"); 
    scanf("%s", &name); 

    read = fopen(name, "r"); 
    if (read == NULL) 
    { 
     perror("Doesn't work"); 
     return 1; 
    } 

    else 
    { 
     array = malloc(100 * sizeof(*array)); 
     while (!feof(read)) 
     { 
      array[i] = malloc(32 * sizeof(*array[i])); 
      fscanf(read, "%s", &array[i]); 
      i++; 

     } 
    } 
} 

Tt编译,但是当我尝试显示它是空的数组。有任何想法吗?

+1

请出示您用来显示数据的代码。 – dasblinkenlight

+0

你显然已经省略了部分代码。 –

+0

并铸造了'malloc()'的返回值。 – 2012-06-29 14:13:03

回答

2
while (!feof(read)) 
    { 
     array[i] = malloc(32 * sizeof(*array[i])); 
     fscanf(read, "%s", array[i]); //You should pass a pointer to a pointer to array of chars 
     i++; 
    } 

我希望它会工作...

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

long GetFileSize(FILE *fp){ 
    long fsize = 0; 

    fseek(fp,0,SEEK_END); 
    fsize = ftell(fp); 
    fseek(fp,0,SEEK_SET);//reset stream position!! 

    return fsize; 
} 

char *ReadToEnd(const char *filepath){ 
    FILE *fp; 
    long fsize; 
    char *buff; 

    if(NULL==(fp=fopen(filepath, "rb"))){ 
     perror("file cannot open at ReadToEnd\n"); 
     return NULL; 
    } 
    fsize=GetFileSize(fp); 
    buff=(char*)malloc(sizeof(char)*fsize+1); 
    fread(buff, sizeof(char), fsize, fp); 
    fclose(fp); 
    buff[fsize]='\0'; 

    return buff; 
} 

char** split(const char *str, const char *delimiter, size_t *len){ 
    char *text, *p, *first, **array; 
    int c; 
    char** ret; 

    *len = 0; 
    text=strdup(str); 
    if(text==NULL) return NULL; 
    for(c=0,p=text;NULL!=(p=strtok(p, delimiter));p=NULL, c++)//count item 
     if(c==0) first=p; //first token top 

    ret=(char**)malloc(sizeof(char*)*c+1);//+1 for NULL 
    if(ret==NULL){ 
     free(text); 
     return NULL; 
    } 
    strcpy(text, str+(first-text));//skip until top token 
    array=ret; 

    for(p=text;NULL!=(p=strtok(p, delimiter));p=NULL){ 
     *array++=strdup(p); 
    } 
    *array=NULL; 
    *len=c; 
    free(text); 
    return ret; 
} 

void free4split(char** sa){ 
    char **array=sa; 

    if(sa!=NULL){ 
     while(*sa) 
      free(*sa++);//for string 
     free(array); //for array 
    } 
} 

int main(){ 
    char *text, **lines; 
    size_t line_count; 

    text=ReadToEnd("data.txt"); 
    lines=split(text, "\r\n", &line_count); 
    free(text); 
    { //test print 
     int i; 
     for(i=0;i<line_count;++i) 
      printf("%s\n", lines[i]); 
    } 
    free4split(lines); 

    return 0; 
} 
相关问题