Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

31
Oct

Convert DOS, UNIX, APPLE Line Feeds and Carriage Returns (CR, LF)

Related Blog Items

DOS uses Carriage Return (\r), Line Feed (\n) for line termination, where as UNIX uses only Line Feed for line termination, APPLE uses carriage return for same purpose. Here is a program which makes one operating system’s text file compatible with other operating system’s text file by conevrting the line feeds and carriage returns according to the system.

enum {DOS_TO_UNIX, DOS_TO_APPLE, UNIX_APPLE_TO_DOS};
 
int ConvertCRLF(char* file, int mode)
{
  //LF-CRLF Converts anything (Unix or Apple) to the DOS standard CRLF.
  //CRLF-CR Converts DOS text to the Apple standard CR.
  //CRLF-LF Converts DOS text to the Unix standard LF.
 
  FILE *fp = NULL;
  FILE *wfp = NULL;
  int ch = 0;
 
  fp = fopen(file, "rw+");
  if (!fp)
  {
    return -1;
  }
 
  wfp = fopen("temp.file", "rw+");
  if (!fp)
  {
    return -1;
  }
 
  while(!feof(fp))
  {
    ch = fgetc(fp);
    switch(mode)
    {
      case DOS_TO_UNIX:
        chnext = fgetc(fp);
        if ((ch == '\r') && (chnext == '\n'))
        {
          fputc('\n', wfp);
        }
        else
        {
          fputc(ch, wfp);
          fputc(chnext, wfp);
        }
        break;
      case DOS_TO_APPLE:
        chnext = fgetc(fp);
        if ((ch == '\r') && (chnext == '\n'))
        {
          fputc('\r', wfp);
        }
        else
        {
          fputc(ch, wfp);
          fputc(chnext, wfp);
        }
        break;
      case UNIX_APPLE_TO_DOS:
        if ((ch == '\r') || (ch == '\n'))
        {
          fputc('\r', wfp);
          fputc('\n', wfp);
        }
        else
        {
          fputc(ch, wfp);
        }
        break;
     }
  }
  return 0;
}

Popularity: 9%

You need to log on to convert this article into PDF


Related Blog Items

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image