Text Files vs Binary Files and C++ File Opening Modes

Posted by Anonymous and classified in Computers

Written on in English with a size of 3.81 KB

1. Compare text files and binary files with respect to storage, processing speed, memory utilization, and applications.

Comparison Between Text Files and Binary Files

BasisText FilesBinary Files
StorageData is stored as characters (ASCII/Unicode). Numbers are stored in readable form.Data is stored in binary (0s and 1s) in the format used by the computer.
Processing SpeedGenerally slower because data may need to be converted between characters and internal formats.Generally faster because data can be read/written in its native binary format.
Memory UtilizationUsually requires more storage space, especially for numerical data.Usually requires less storage space because data is stored more compactly.
ReadabilityHuman-readable; can be opened with Notepad or a text editor.Not human-readable; requires a suitable program to interpret the data.
ApplicationsUsed for source code, configuration files, logs, .txt files, etc.Used for images, videos, audio, executable files, databases, etc.
PortabilityGenerally more portable because different systems can easily interpret text.May depend on the system/program and the format in which the binary data is stored.

Simple Example:

  • Text file: Dhruv 18 85 — The information is stored as readable characters.
  • Binary file: The same information is stored in binary form according to the computer's data representation, so opening it in a normal text editor may show unreadable symbols.

2. Explain various file opening modes available in C++. Discuss the significance of each mode with suitable examples.

File Opening Modes in C++

File opening modes specify how a file should be opened for reading, writing, appending, etc.

1. ios::in — Reading

  • Used to read data from a file.
  • The file must generally exist.
ifstream file("data.txt", ios::in);

2. ios::out — Writing

  • Used to write data into a file.
  • Creates the file if it does not exist.
  • Existing contents are normally overwritten.
ofstream file("data.txt", ios::out);
file << "Hello World";

3. ios::app — Append

  • Adds new data at the end of the file.
  • Existing data is preserved.
ofstream file("data.txt", ios::app);
file << "New line";

4. ios::ate — At End

  • Opens the file with the file pointer initially at the end.
  • The pointer can be moved to another position.
fstream file("data.txt", ios::in | ios::ate);

5. ios::trunc — Truncate

  • Deletes existing contents when the file is opened for writing.
  • New data can be written to the empty file.
ofstream file("data.txt", ios::out | ios::trunc);

6. ios::binary — Binary Mode

  • Opens a file in binary mode.
  • Used for images, audio, video, and other binary data.
ifstream file("image.jpg", ios::in | ios::binary);

Related entries: