If the input file is opened in binary mode (the "b" character in the mode line), then you need to worry about the possible presence of '\r' to '\n' .
If the file does not open in binary mode (and also cannot be read using binary functions such as fread() ), then there is no need to worry about the presence of '\r' to '\n' , because this will be processed before the input received by your code - either using the appropriate system function (for example, a device driver that reads input from disk, or from stdin ), or by implementing functions that you use to read input from a file.
If you transfer files between systems (for example, writing a file under Linux and transferring it to the Windows system, where the program tries to read it), you have options;
- write and read the file in binary mode and perform the appropriate translation of the file when it is transferred between systems. If you use
ftp , this can be accomplished by transferring the file in text mode rather than binary mode. If the file is transmitted in binary mode, you will need to run the file using dos2unix (when transferring the file to unix) or through unix2dos (going the other way). - Perform all I / O operations in binary mode, transfer them between systems using binary mode, and never read them in binary mode. Among other things, it gives you clear control over what data is in the file.
- Write your file in text mode, transfer the file as you wish. Then read only in binary mode and when your reading code encounters a pair
\r\n , omit the character '\r' .
The latter is probably the most reliable - the write code may include \r before the \n characters, or it may not be, but the read code just ignores any '\r' characters it encounters before the '\n' character '\n' the code will probably even cope if the files are edited manually (for example, using a text editor that can be separately configured to insert or delete \r and \n ) before reading.
Peter source share