Thread: fgetc() skips carriage returns?

  1. #1
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Umeċ, Sweden

    Thumbs up fgetc() skips carriage returns?

    I am reading a file which is a map file for my snake clone which I am writing in SDL and creating it from scratch. The field consists of 40x40 blocks and so the map file consists of 40 rows and 40 characters on each row. I wanted the program to be able to read the file for the three different line endings, LF, CRLF and CR but I kept getting errors which I tracked down what seems to be fgetc()'s inability to read CRs.

    I had the program write the character in hex and the current column for each iteration to stderr.
    The output from stderr looks like this in my text editor:
    1:    0x2E 0
    2:    0x2E 1
    3:    0x2E 2
    39:    0x2E 38
    40:    0x2E 39
    41:    0x2E 40
    42:    0x2E 0
    43:    0x2E 1
    44:    0x2E 2
    The CR should be at 40, but instead it skips to the next character.

    The code which parses newlines:
    if (i == 40) {
    	if (!(c == '\r' || c == '\n')) {
    		fprintf(stderr, "Error: Parse error; expected newline in map file on line %d. Got ascii code 0x%02X.", j+1, c);
    	if (c == '\r') { //For Windows newlines
    		if ((c = fgetc(map)) != '\n') {
    			ungetc(c, map);
    	i = 0;
    So the current code can only handle LF and CRLF (since it skips CR, it will think of CRLF as LF).
    Is this a problem or will it work when compiled in an environment that uses CR for line endings?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    If you open the file as a text file, the only end of line character you should see is a '\n', no matter what platform you're on (assuming said text file is stored in native text file format).

  3. #3
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Umeċ, Sweden
    I had completely forgotten about the difference of opening a file as text or binary.
    So this means that the newline parser is unnecessary and I can just replace it with a simple "if (c != '\n')"?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Polynomials and ADT's
    By Emeighty in forum C++ Programming
    Replies: 20
    Last Post: 08-19-2008, 08:32 AM
  2. Finding carriage returns (\c) in a line
    By JizJizJiz in forum C++ Programming
    Replies: 37
    Last Post: 07-19-2006, 05:44 PM
  3. fgetc - returns immediately?
    By sean in forum C Programming
    Replies: 2
    Last Post: 12-11-2004, 09:24 AM
  4. fgetc() and getc()
    By The Dog in forum C Programming
    Replies: 2
    Last Post: 07-24-2002, 05:00 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
Website Security Test