Skip to content

Instantly share code, notes, and snippets.

@codebrainz
Created October 15, 2011 02:08
Show Gist options
  • Select an option

  • Save codebrainz/1288896 to your computer and use it in GitHub Desktop.

Select an option

Save codebrainz/1288896 to your computer and use it in GitHub Desktop.
Guess the line-endings mode of a text buffer
typedef enum
{
LINE_END_MODE_CR,
LINE_END_MODE_LF,
LINE_END_MODE_CRLF
}
LineEndMode;
LineEndMode guess_line_endings(const char* buffer, size_t size)
{
# define MAX_LINES 10
size_t i;
unsigned int cr, lf, crlf, max_mode;
LineEndMode mode;
cr = lf = crlf = 0;
for (i = 0; i < size ; i++)
{
if (buffer[i] == 0x0a)
{
/* LF */
lf++;
}
else if (buffer[i] == 0x0d)
{
if (i >= (size - 1))
{
/* Last char, CR */
cr++;
}
else
{
if (buffer[i + 1] != 0x0a)
{
/* CR */
cr++;
}
else
{
/* CRLF */
crlf++;
}
i++;
}
}
if ((lf + cr + crlf) > MAX_LINES)
break;
}
/* Vote for the maximum */
mode = LINE_END_MODE_LF;
max_mode = lf;
if (crlf > max_mode)
{
mode = LINE_END_MODE_CRLF;
max_mode = crlf;
}
if (cr > max_mode)
{
mode = LINE_END_MODE_CR;
max_mode = cr;
}
return mode;
# undef MAX_LINES
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment