Force C to stop interpreting newlines differrent from CR LF

Viewed 58

My program read a Windows text file line by line, using fgets with MinGW. Each line is ended by CR LF ('\r', '\n'). The text file is generated by tools and sometimes contains the character '\n' in the data.

I found out that fgets ignores every character after the '\n' and part of my data is missing.

How to change this behavior, so that:

  • Single '\n' are treated as a normal character
  • '\r' '\n' is treated as new line

Edit: I found out that some double-quoted strings in my file do have '\n' in the data, but also do have '\r' '\n' in the data somtimes. Unfortunately, I cannot fix the tools. So I had to write some code, as suggested in the valuable comments.

1 Answers

As suggested in the comments, I posted here the code I wrote to fix the issue. The code is probably buggy, posted below as reference:

static void DIRTY_ReadLine (FILE     *File,
                            uint8_t  *Buffer,
                            uint32_t  BufferSizeInBytes)
{
  uint8_t  *pChar = Buffer;
  uint32_t  ByteCount;
  int32_t   Character;
  int32_t   PreviousCharacter;
  bool      NewLineFound;
  bool      InsideString;

  Character         = fgetc(File);
  PreviousCharacter = 0;
  NewLineFound      = false;
  InsideString      = false;
  ByteCount         = 0;

  while (!NewLineFound
         && (Character != EOF)
         && (ByteCount < BufferSizeInBytes))
  {
    if (!InsideString
        && (PreviousCharacter == '\r')
        && (Character == '\n'))
    {
      pChar--;
      *pChar       = '\0';
      NewLineFound = true;
    }
    else
    {
      if (Character == '\"')
      {
        InsideString = !InsideString;
      }      
      *pChar            = (uint8_t)Character;
      PreviousCharacter = (uint8_t)Character;
      pChar++;
      ByteCount++;
      Character = fgetc(File);
    }
  }
}
Related