使用文件

时间:2017-11-19 17:02:24

标签: c malloc realloc

我想要做的就是读取文件内容并将它们放到字符串中 从文件中读取时出现问题。我开始用fgets阅读,如果我的空间不够,我会重新分配内存。但是,当我尝试再次重新分配以缩小时,它会崩溃。我读到它可能与malloc的元数据有关,但我看不出我是如何影响它们的。提前致谢

 int readStringFromALE(int height,int width,char **stringImage,FILE *fout){
    char buffer[BUFFER_SIZE] = {'\0'};
    *stringImage=(char *)malloc(sizeof(char)*BUFFER_SIZE+1);
    *stringImage[0]='\0';
    int i=1;
    int size=sizeof(char)*BUFFER_SIZE,readSize=0;
    while(fgets(buffer, sizeof(buffer), fout) != NULL){
        strncat(*stringImage,buffer,strlen(buffer)+1);
        readSize+=strlen(buffer)+1;
        printf("%s",buffer);
        if(size<=readSize){
            char *temp;
            temp=(char *)realloc(*stringImage,i*BUFFER_SIZE*sizeof(char)+1);
            if(temp==NULL){
                printf("Unable to allocate memory\n");
                return EXIT_FAILURE;
            }
            i++;
            *stringImage=temp;
            size=i*BUFFER_SIZE*sizeof(char);
        }
        if (buffer[strlen(buffer) - 2] == ':')
            break;
    }
    char *temp=(char *)realloc(*stringImage,strlen(*stringImage)+10);
    if(temp==NULL){
        printf("Unable to allocate memory\n");
        return EXIT_FAILURE;
    }
    *stringImage=temp;
    return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:1)

尝试在每次调用时使用fgets读取字符串末尾(* stringImage + len)。

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

#define BUFFER_SIZE 10

int readStringFromALE(int height,int width,char **stringImage,FILE *fout){
    char *temp = NULL;
    size_t size = 0;
    size_t dif = 0;
    size_t len = 0;

    while ( 1) {
        if ( NULL == ( temp = realloc ( *stringImage, size + BUFFER_SIZE))) {
            fprintf ( stderr, "problem realloc\n");
            free ( *stringImage);
            return 0;
        }
        *stringImage = temp;
        //len = strlen ( *stringImage);
        dif = BUFFER_SIZE + ( size - len);
        if ( fgets ( *stringImage + len, dif, fout)) {
            len += strlen ( *stringImage + len);
            if ((*stringImage)[strlen(*stringImage) - 2] == ':')
                break;
        }
        else {
            printf("\n\n---end of file---\n");
            break;
        }
        size += BUFFER_SIZE;
    }
    temp=(char *)realloc(*stringImage,strlen(*stringImage)+10);
    if(temp==NULL){
        printf("Unable to allocate memory\n");
        return EXIT_FAILURE;
    }
    *stringImage=temp;
    return EXIT_SUCCESS;
}

int main(int argc,char** argv){
    char *stringImage = NULL;//so realloc will act like malloc on first call
    int height = 0;
    int width = 0;
    FILE *fout = NULL;

    if ( NULL == ( fout = fopen ( "somefile.txt", "r"))) {
        perror ( "problem");
        return 0;
    }

    readStringFromALE( height, width, &stringImage, fout);
    fclose ( fout);
    printf("%s\n\n",stringImage);

    free ( stringImage);

    return 0;
}