Introduction
In the past, if you wanted to read files, there was a restriction. You can not predict how long a line can be present at the read time. So the user has to predict the maximum length of a line that a file could store. But now, using this code, you can read any length of line from your file.
Background
During some programming situation, I needed to read a single line from a text file. At that time, I predicted that the maximum line length would be 1024 or 2048 characters long.
Using the code
Here is the ReadLine
function code:
int ReadLine(char** pszBuffer, FILE * pFilePtr)
{
char szBuffer[1024] = {0}; char *pcRes = NULL; int nNl = 0;
if(*pszBuffer != NULL){
free(*pszBuffer);
}
*pszBuffer = (char *) malloc(sizeof(szBuffer) + 1);
**pszBuffer = '\0';
while((pcRes = fgets(szBuffer, sizeof(szBuffer), pFilePtr)) != NULL){
*pszBuffer = realloc(*pszBuffer, strlen(szBuffer) +
strlen(*pszBuffer) + 1);
if(*pszBuffer == NULL){
printf("\n Memory error");
return 0;
}
strcat(*pszBuffer, szBuffer);
strcpy(szBuffer, "");
nNl = strlen(*pszBuffer) - 1;
if((*pszBuffer)[nNl] == '\n'){
break;
}
}
return 1;
}