从文件读取到字符数组

时间:2012-06-29 14:04:45

标签: c arrays file char scanf

我正在尝试读取从文件到数组的字符串列表。 在文件中它看起来像这样

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

2 个答案:

答案 0 :(得分: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++;
    }

我希望它能起作用......

答案 1 :(得分: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;
}