linux - Is it necessary to write a "portable" if (c == '\n') to process cross-platform files? -
this thinking comes discussion practical problem replacing multiple new lines in file one. wrong happened while using cygwin terminal running on windows 8.1 machine.
since end-of-line terminator different, \n
, \r
, or \r\n
, necessary write "portable" if(c=='\n')
make work on linux, windows , os x? or, the best practise convert file commands/tools?
#include <stdio.h> int main () { file * pfile; int c; int n = 0; pfile=fopen ("myfile.txt","r"); if (pfile==null) perror ("error opening file"); else { { c = fgetc (pfile); if (c == '\n') n++; // work fine under different platform? } while (c != eof); fclose (pfile); printf ("the file contains %d lines.\n",n); } return 0; }
update1:
crt convert line endings '\n'?
if input file opened in binary mode (the character 'b' in mode string) necessary worry possible presence of '\r'
before '\n'
.
if file not opened in binary mode (and not read using binary functions such fread()
) not necessary worry presence of '\r'
before '\n'
because handled before input received code - either relevant system function (e.g. device driver reads input disk, or stdin
) or implementation of functions use read input file.
if transferring files between systems (e.g. writing file under linux, , transferring windows system, program tries read in) have options;
- write , read file in non-binary mode, , relevant translation of file when transferring between systems. if using
ftp
can handled transferring file using text mode rather binary mode. if file transferred in binary mode, need run file throughdos2unix
(if transferring file unix) or throughunix2dos
(going other way). - do i/o in binary mode, transfer them between systems using binary mode, , never read them in non-binary mode. among other things, gives explicit control on data in file.
- write file in text mode, transfer file see fit. read in binary mode and, when reading code encounters
\r\n
pair, drop'\r'
character.
the last arguably robust - writing code might include \r
before \n
characters, or might not, reading code ignores '\r'
characters encounters before '\n'
character. such code cope if files edited hand (e.g. text editor - might separately configured either insert or remove \r
, \n
) before being read.
Comments
Post a Comment