I am trying to learn how to dynamically allocate memory for very long lines when I'm reading a file. I search on here and web and I tried some code.
Firstly, here is my first non-dynamic code:
char line[256];
file = fopen(inputFileName, "r");
// Here, of course I checked file is opened or not.
while (fgets(line, sizeof(line), file)) {
// do some operations
}
// Closing operations
This works for me when I reading files. But here is line must be equal or less than 255 characters. So, I want to read for example 300 character length line from file.
I tried following code:
size_t maxl = 256;
//char line[256];
char *line = malloc(maxl * sizeof(char));
if(!line){
printf("Memory not allocated!!\n");
return -2;
}
file = fopen(inputFileName, "r");
while (fgets(line, sizeof(line), file)) {
while(line[strlen(line) - 1] != '\n' || line[strlen(line) - 1] != '\r'){
char *tmp = realloc (line, 2 * maxl);
//fgets(line, sizeof(line), file);
if (tmp) {
line = tmp;
maxl *= 2;
}
else{
printf("Not enough memory for this line!!\n");
return -3;
}
}
// do some operations
}
I tried to implement answers in this question actually: Reading a line from file in C, dynamically
But it always enter "Not enough memory" part of the code. So, what am I doing wrong?
Thank you already for your answers and advises.
Edit: Code is updated depend on first comments.
Edit 2: Code is always read same 3 characters from the file.
Imagine that the file is like:
abcdabcdabcd...
The line
variable is always "abc" even after re-allocation operation.