0

When we work with text files in C language, we can use "\n" for writing a "newline" in the text file. However, depending on the operating system, this character is stored differently on the file.

Unix uses LF (line feed)​ Mac OS uses CR (carriage return)​ Microsoft Windows uses CR+LF​

So, when we open a text file for reading it, I think that we need to consider that the format of the text file is different and dependent on the OS. Am I correct?

If this is correct, how to deal efficiently in my C program with files that can be produced in different OS?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Zaratruta
  • 2,097
  • 2
  • 20
  • 26
  • open files in text mode, use `fopen("path", "rt")` – tstanisl Oct 25 '21 at 15:20
  • @tstanisl Text mode is the default. – Barmar Oct 25 '21 at 15:24
  • 1
    @tstanisl Text mode assumes the file is written using the local newline convention. It won't help if the file is copied from a different OS. – Barmar Oct 25 '21 at 15:24
  • @tstanisl Also the `t` is a Windows and VC++ CRT extension, not standard. – Some programmer dude Oct 25 '21 at 15:25
  • 1
    FYI, MacOS hasn't used `CR` since MacOS 9. It's now based on Unix and uses `LF`. – Barmar Oct 25 '21 at 15:25
  • 2
    @tstanisl I'm not familiar with `"t"` for `fopen`. But, using text mode [the default] won't work if (e.g.) we're on linux/unix [which expects `\n`] and we try to process a file written on MacOS [which writes `\r`]. – Craig Estey Oct 25 '21 at 15:25
  • Unless you need to transfer the file between different operating systems with different line-endings, you should not need to do anything. The system should have automatic translation of `\n` to the proper newline sequence when writing, and the opposite translation when reading. – Some programmer dude Oct 25 '21 at 15:26
  • @Someprogrammerdude, ok, but my question is exactly about how to deal with files that could potentially be created in different OS. – Zaratruta Oct 25 '21 at 15:29
  • @tstanisl *open files in text mode, use `fopen("path", "rt")`* [That appears to be a non-standard, platform-specific extension](https://port70.net/~nsz/c/c11/n1570.html#7.21.5.3). – Andrew Henle Oct 25 '21 at 16:03
  • 2
    Then either do as text-editors often do and read the whole file checking all possible line-endings, and deduce the one most used and use that (with your own translation as needed); Or add a setting in the program to set the line-endings, and again do your own translation. – Some programmer dude Oct 25 '21 at 16:05

0 Answers0