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 编译,但是当我尝试显示数组时它是空的。有任何想法吗?

4

2 回答 2

1
    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++;
    }

我希望它会工作...

于 2012-06-29T14:17:49.573 回答
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;
}
于 2012-06-30T04:10:11.603 回答