fgetc
int NextChar;
if ((NextChar = fgetc(File1)) == EOF) //Returns character read as an unsigned char or EOF on end of file or error
{
//END OF FILE REACHED
}
else
{
*pDest++ = (char)NextChar;
}
fgets
Return next line from a file, or the portion of it up to the buffer size limit:
char LineBuffer[30];
while (fgets(LineBuffer, sizeof(LineBuffer), File1))
{
A better way of doing it
fgets() doesn’t add a null character at the end of the read data and on some systems can fail to handle mac formatted text files correctly (0x0d only line endings). The following code ensures there is a terminating null, handles all line-ending character possibilities and also handles lines that are too long by dumping the remainder of the line (you can change that behaviour if you want):
//Returns pointer to start of the line, or 0x00 if EOF and no bytes read
char *fgets_our_version (char *LineBuffer, int Size, FILE *File1)
{
int Index;
static int GetcNext = -1; //Needs to be retained for the next call
int GetcPrevious;
Index = 0;
while (1)
{
GetcPrevious = GetcNext;
GetcNext = fgetc(File1);
if (GetcNext == EOF)
{
//ESP_LOGI(TAG, "Got EOF");
//Error or end of file
LineBuffer[Index] = 0x00;
if (Index == 0)
return (0x00);
else
return (LineBuffer);
}
else if (
(GetcPrevious == '\r') &&
(GetcNext == '\n')
)
{
//Ignore [0x0a] when line ending is [0x0d][0x0a]
//ESP_LOGI(TAG, "Got CRNL");
}
else if (
(GetcNext == '\r') || //We handle line endings with [0x0a] (Linux), [0x0d][0x0a] (Windows), [0x0d] (Mac)
(GetcNext == '\n')
)
{
//End of line
//ESP_LOGI(TAG, "Got NL");
LineBuffer[Index] = 0x00;
return (LineBuffer);
}
else
{
//Get next character
if (Index < (Size - 1)) //Leave space for the terminating null
LineBuffer[Index++] = (char)GetcNext;
}
}
}
fread
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through resources like this. We hope you find it helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support here. If you need help with a problem please use one of the many online forums.