Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between files written in binary and text mode

Tags:

c++

c

file-io

What translation occurs when writing to a file that was opened in text mode that does not occur in binary mode? Specifically in MS Visual C.

unsigned char buffer[256]; for (int i = 0; i < 256; i++) buffer[i]=i; int size  = 1; int count = 256; 

Binary mode:

FILE *fp_binary = fopen(filename, "wb"); fwrite(buffer, size, count, fp_binary); 

Versus text mode:

FILE *fp_text = fopen(filename, "wt"); fwrite(buffer, size, count, fp_text); 
like image 826
jholl Avatar asked Oct 23 '08 14:10

jholl


People also ask

What is the difference between text and binary files?

Text files are organized around lines, each of which ends with a newline character ('\n'). The source code files are themselves text files. A binary file is the one in which data is stored in the file in the same way as it is stored in the main memory for processing.

What is the difference between text files and binary files in C?

The major difference between these two is that a text file contains textual information in the form of alphabets, digits and special characters or symbols. On the other hand, a binary file contains bytes or a compiled version of a text file.

Why are binary files better than text files?

Text files are used to store data more user friendly. Binary files are used to store data more compactly. In the text file, a special character whose ASCII value is 26 inserted after the last character to mark the end of file. In the binary file no such character is present.

What is binary mode in files?

Binary mode allows programmers to manipulate files byte by byte rather than in larger logical structures.


1 Answers

I believe that most platforms will ignore the "t" option or the "text-mode" option when dealing with streams. On windows, however, this is not the case. If you take a look at the description of the fopen() function at: MSDN, you will see that specifying the "t" option will have the following effect:

  • line feeds ('\n') will be translated to '\r\n" sequences on output
  • carriage return/line feed sequences will be translated to line feeds on input.
  • If the file is opened in append mode, the end of the file will be examined for a ctrl-z character (character 26) and that character removed, if possible. It will also interpret the presence of that character as being the end of file. This is an unfortunate holdover from the days of CPM (something about the sins of the parents being visited upon their children up to the 3rd or 4th generation). Contrary to previously stated opinion, the ctrl-z character will not be appended.
like image 177
Jon Trauntvein Avatar answered Sep 19 '22 14:09

Jon Trauntvein