fgetc

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

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *