我想做的只是读取文件内容并将它们放入字符串中。
我在读取文件时遇到问题。我开始用fgets阅读,如果我的空间不够,我会重新分配内存。但是,当我尝试再次重新分配以缩小时,它崩溃了。我读到它可能与 malloc 的元数据有关,但我看不出我如何影响它们。提前致谢
int readStringFromALE(int height,int width,char **stringImage,FILE *fout){
char buffer[BUFFER_SIZE] = {' '};
*stringImage=(char *)malloc(sizeof(char)*BUFFER_SIZE+1);
*stringImage[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 memoryn");
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 memoryn");
return EXIT_FAILURE;
}
*stringImage=temp;
return EXIT_SUCCESS;
}
尝试在每次调用时使用 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 reallocn");
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("nn---end of file---n");
break;
}
size += BUFFER_SIZE;
}
temp=(char *)realloc(*stringImage,strlen(*stringImage)+10);
if(temp==NULL){
printf("Unable to allocate memoryn");
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("%snn",stringImage);
free ( stringImage);
return 0;
}