Well getting to the point... I'm trying to read the content of a file to memory. Each line goes into a string of characters. Problem is some of the data gets overwritten with pieces of other data also from the file (yeah it's a little confusing). Here's a piece of code, hopefully you'll see something I missed:
FILE *file;
char **buff;
char ch;
int lines,i;
if(!(file=fopen("file.txt","rt")))
return;
lines=flines(filename); // flines just returns the number of lines in the file
buff=(char**)malloc(sizeof(char*)*lines);
for(i=0;i<lines;i++){
buff[i]=(char*)malloc(sizeof(char)+1);
ch=fgetc(file);
sprintf(buff[i],"%c%c",ch,'\0');
while((ch=fgetc(file)) != '\n'){
if(ch == EOF) break;
buff[i]=(char*)realloc(buff[i],strlen(buff[i])+2);
sprintf(buff[i],"%s%c",buff[i],ch);
}
if(ch == EOF) break;
}
Any ideas? It seems to work ok but as I said some data comes out messy. I was wondering if it's a memory issue (all those reallocs...). Oh and just for the record I do take care of the garbage in the memory :-) I just didn't enter the entire code because it's quite big.
Thanks in advance. If I'm not supposed to ask for help in this area feel free to delete my topic and accept my apologies.


Sign In
Create Account

Back to top









