1 year ago
#369540
brobro420
How to solve the \r (carriage return) problem that prevents Windows text files from being cross-platform with Linux?
Intro
There is a "feature" in Windows that adds a carriage return character before every newline. This is an old thing, but I am having trouble finding specific solutions to the problem.
Problem
If you create a file in Windows with fopen("file.txt", "w")
, it will create a text file where every \n
in your code is converted to \r\n
. This creates a problem in situations where you try to read the file on Linux, because there is now an unaccounted-for character in the mix, and most line reads depend on reading to \n
.
Research
I created text ("w") and binary ("wb") files on Windows and Linux, and tried to read and compare them with the same files made on the other OS.
Binary files do not get an added carriage return, and seem to work fine.
Text files, on the other hand, are a mixed bag:
On Windows, comparing the Windows text file (
\r\n
) to the Linux text file (\n
) will result in them being read equally (this is apparently a feature of some C Windows implementations -\r\n
will get automatically read as\n
)On Linux, comparing the files will result in them not being equal and the
\r
will not be handled, creating a reading problem.
Conclusion I would like to know of ways how to handle this so my text files can be truly cross-platform. I have seen a lot of posts about this, but most have mixed and opposing claims and almost none have specific solutions. So please, can we solve this problem once and for all after 40 years? Thank you.
c
linux
windows
cross-platform
0 Answers
Your Answer