I've taken a look at the function you wrote and it seems to work nicely. I'm going to play with it a little bit and see if I can figure out what's happening in it.
One thing though; it would not compile with
block = ok +block -result -1; in it on my compiler (Dev-Cpp is my IDE), but upon commenting it out, it compiled and still seemingly works fine. What is that line for?
Edit: My question before still stands. I would still like to know what that line was for. Also, I have written my own function based on yours. It's not as dynamic, as the block sizes are hard-coded, but I would like to know how mine compares to yours and such. You see, I actually have never used malloc or realloc before, so I'm trying to get a grasp of what they're doing.
Here's my function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
char* readLine(FILE *file) {
char *line, *block, *ok;
int lastChar, size = 50;
block = line = (char*)malloc(size);
if(!line) return NULL;
*line = '\0';
do {
ok = (char*)realloc(line, size += 50);
if(!ok) break;
ok = fgets(block, 50, file);
if(!ok) break;
lastChar = strlen(block) - 1;
} while(block[lastChar] != '\n');
if(!(*line)) {
free(line);
line = NULL;
}
return line;
}
|
Like I said, I've never used malloc and realloc and based this completely off of your code. So, I would appreciate any critiquing that you may provide. I'll be looking up the specifics of those functions, as well, and seeing if that helps me understand why this works.
Thank you for your help up until now =)