Home > Blockchain >  Binary mode and Text mode in File I/O in C
Binary mode and Text mode in File I/O in C

Time:10-08

I am little confused when to open a file in Text Mode or Binary Mode. I read some documentations and examples, observed that it used getc()-putc() or fgets()-fputs() in Text Mode as well as in Binary Mode. Can I open a file in Text Mode to use fread()-fwrite() or I should use only Binary Mode for Binary I/O functions like fread()-fwrite(). To use fseek(), ftell() which mode I should use Text Mode or Binary Mode ?

I am using C programming language and Linux distro (fedora).

CodePudding user response:

You can use fread and fwrite in both text and binary, although they are used more commonly for binary. You can use also fseek and ftell in both modes (wb (Write-Binary) and w(Write-Text))

CodePudding user response:

In Unix systems (and linux, in particular), there's no difference between binary mode and text mode (the library just ignores the t qualifier) but in other systems do. In Windows, a line end is indicated with a sequence of \r\n characters, which are converted in input into \n, while when outputting, the \n is converted into a sequence of \r\n for text files. Binary files are not converted at all, so no transformation is done, either in input or in output. You must have present that this transformation is not reversible, as you don't know if the characters or sequences are converted because they where converted in the process or they where already in the form read.

Text mode means that your file is text, and will be transformated to comply with the operating system's way of line ending. If it is actually text, normally this is not a problem, but if you do this with an actually binary file (e.g. a compressed file or a .jpg image) the results will be unpredictable.

  • Related