M
mazwolfe
Someone recently asked about reading lines. I had this code written
some time ago (part of a BASIC-style interpreter based on H. Shildts
in Art of C) to read a file with the lines ended in any format:
Microsoft-style CR/LF pair, Unix-style NL, or Mac-style CR. It also
allows for EOF that does not follow a blank line. I thought this would
make text-file sharing a bit easier.
Here it is:
/* Load a file, normalizing newlines to *nix standard (just NL). */
int load_file(FILE *fp, char *buf, int max_size)
{
int i = 0;
char c;
do {
c = getc(fp); /* read the file into memory */
i++; /* keep track of size of file*/
if (c == '\r') { /* read a CR */
c = getc(fp); /* read another character */
if (c != '\n') { /* whoops, not an NL (Mac style) */
*buf++ = '\n'; /* correct, store NL */
i++; /* and update size */
} /* otherwise, c now holds the NL from the CR/NL pair */
} /* c now holds character to put; NL, (CR/)LF, or (new) char
*/
*buf++ = c;
} while ( !feof(fp) && i < max_size );
/* Null terminate the file, check for NL (LF) at end. */
if (buf[-1] != '\n') /* if file didn't end in new line */
*buf++ = '\n', i++; /* tack it on */
*buf = '\0'; /* put null past file */
fclose(fp);
return i; /* size of file loaded */
}
This allows the file to use a mix of different EOLs. Is that a bad
idea?
-- Marty (I still consider myself a newbie)
some time ago (part of a BASIC-style interpreter based on H. Shildts
in Art of C) to read a file with the lines ended in any format:
Microsoft-style CR/LF pair, Unix-style NL, or Mac-style CR. It also
allows for EOF that does not follow a blank line. I thought this would
make text-file sharing a bit easier.
Here it is:
/* Load a file, normalizing newlines to *nix standard (just NL). */
int load_file(FILE *fp, char *buf, int max_size)
{
int i = 0;
char c;
do {
c = getc(fp); /* read the file into memory */
i++; /* keep track of size of file*/
if (c == '\r') { /* read a CR */
c = getc(fp); /* read another character */
if (c != '\n') { /* whoops, not an NL (Mac style) */
*buf++ = '\n'; /* correct, store NL */
i++; /* and update size */
} /* otherwise, c now holds the NL from the CR/NL pair */
} /* c now holds character to put; NL, (CR/)LF, or (new) char
*/
*buf++ = c;
} while ( !feof(fp) && i < max_size );
/* Null terminate the file, check for NL (LF) at end. */
if (buf[-1] != '\n') /* if file didn't end in new line */
*buf++ = '\n', i++; /* tack it on */
*buf = '\0'; /* put null past file */
fclose(fp);
return i; /* size of file loaded */
}
This allows the file to use a mix of different EOLs. Is that a bad
idea?
-- Marty (I still consider myself a newbie)