'Passing FILE* as parameter
I know this is a common question but answers are varying a lot depending on context and not only have the found contexts been way simpler but also the found solutions haven't worked so far.
char* loadText(FILE** f, char* text){
int nbytes, bufferSize = BUFFERSIZE;
char* buff = (char*) malloc(sizeof(char) * bufferSize);
while(1){
nbytes = fread(buff, sizeof(char), bufferSize, *f);
if(nbytes == bufferSize){
bufferSize *= 2;
buff = (char*) malloc(sizeof(char) * bufferSize);
}
else break;
}
text = buff;
return text;
}
int main(){
FILE* f = fopen("sometextfile.txt", "read");
char* text;
text = loadText(&f, text);
fclose(f);
printf("%s", text);
return 0;
}
There is no output. I've also tried with loadText(File* f, char* text). Same results. What am I doing wrong?
Solution 1:[1]
char* loadText(FILE* f, char **text)
{
size_t nbytes = 0, bufferSize = BUFFERSIZE;
char* buff = malloc(bufferSize);
if(!buff){/*error handling*/}
while(1){
nbytes += fread(buff + nbytes, 1, bufferSize - nbytes, f);
if(nbytes == bufferSize)
{
char *tmp;
bufferSize *= 2;
tmp = realloc(buff, bufferSize);
if(tmp) buff = tmp;
else {/*error handling*/}
}
else break;
}
*text = buff;
return *text;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 0___________ |
