Table of Contents

    Text File vs Binary File

    Chapter 17.6

    Text File vs Binary File

    Learn the difference between text files and binary files in programming, how they store data, how programs read and write them, common examples, advantages, limitations, and when to use each type in real-world applications.

    Introduction

    In programming, files are commonly used to store data permanently. However, not all files store data in the same way. Based on how data is stored and interpreted, files are mainly divided into two broad types: text files and binary files.

    A text file stores data in a human-readable format. This means you can usually open it using a simple text editor and understand the content. Examples include .txt, .csv, .json, .xml, .html, and .log files.

    A binary file stores data in a format that is not directly readable by humans. Binary files store data as raw bytes, and they usually require a specific program to open or interpret them correctly. Examples include images, audio files, videos, PDF files, compiled programs, and database files.

    "Text files store data in a human-readable character format, while binary files store data in raw byte format."

    Simple Definition

    A text file is a file that stores information as readable characters. A binary file is a file that stores information as bytes, usually in a format designed for computers or specific software rather than direct human reading.

    BASIC IDEA
    Text File = Readable Characters   |   Binary File = Raw Bytes

    In simple words:

    • Text files are easier for humans to read and edit.
    • Binary files are usually more efficient for storing complex data.
    • Text files commonly store plain text, records, configuration, and structured data.
    • Binary files commonly store images, audio, video, applications, and compressed data.
    • Text files are usually handled using character encoding such as UTF-8.
    • Binary files are handled using byte-level reading and writing.
    Important: The file extension alone does not always guarantee the internal format. A program should handle a file according to how the data is actually stored.

    Prerequisites

    Before learning the difference between text files and binary files, students should understand some basic programming and file handling concepts.

    Prerequisite Topic Why It Is Needed
    Files and Folders To understand how data is stored permanently on a computer.
    Reading Files To understand how programs load data from files.
    Writing Files To understand how programs save data into files.
    File Paths To locate files correctly during file operations.
    Strings Text file content is commonly processed as string data.
    Bytes Binary files are usually processed as byte data.
    Character Encoding To understand how text characters are stored internally.

    What is a Text File?

    A text file is a file that stores data as readable text characters. These characters may include letters, numbers, symbols, spaces, tabs, and line breaks. Text files are commonly used when data needs to be easily viewed, edited, shared, or processed by humans and programs.

    You can usually open a text file using applications such as Notepad, VS Code, Sublime Text, TextEdit, or any basic text editor. If the file contains plain text, you can read and understand its content directly.

    Examples of text files include:

    • .txt files for plain notes or records.
    • .csv files for table-like data.
    • .json files for structured key-value data.
    • .xml files for tag-based structured data.
    • .html files for web page structure.
    • .css files for website styling rules.
    • .js, .java, .php, and other source code files.
    • .log files for application logs.

    Text File Analogy

    A text file is like a notebook. You can open it, read the content, edit it, and understand it without needing special decoding software.

    Example of Text File Content

    A text file may contain simple student records like this:

    
    Student ID: S101
    Name: Rahul
    Course: Programming Fundamentals
    Marks: 85
    Grade: B
    

    A CSV text file may contain data like this:

    
    studentId,name,course,marks
    S101,Rahul,Programming Fundamentals,85
    S102,Ayesha,Programming Fundamentals,92
    S103,John,Programming Fundamentals,76
    

    A JSON text file may contain structured data like this:

    
    {
        "studentId": "S101",
        "name": "Rahul",
        "course": "Programming Fundamentals",
        "marks": 85,
        "grade": "B"
    }
    

    All these examples are text-based because the content can be opened and understood by humans.

    What is a Binary File?

    A binary file is a file that stores data as raw bytes. Unlike text files, binary files are not designed to be directly read by humans. They usually require specific software to interpret the stored bytes correctly.

    For example, an image file stores pixel information, color data, compression data, and metadata in binary form. If you open an image file in a simple text editor, you may see strange characters because the data is not stored as normal readable text.

    Examples of binary files include:

    • .jpg, .png, .gif image files.
    • .mp3, .wav audio files.
    • .mp4, .avi, .mkv video files.
    • .pdf document files.
    • .exe executable program files.
    • .zip, .rar compressed archive files.
    • .dat custom binary data files.
    • .db database files.

    Binary File Analogy

    A binary file is like a machine-readable package. Humans may not understand it directly, but the correct program can interpret it and display meaningful output.

    Example of Binary File Behavior

    Suppose you open an image file such as photo.jpg in a normal text editor. Instead of seeing a meaningful picture, you may see unreadable symbols or strange characters. That happens because the image is stored as binary data.

    The image viewer understands the binary format and converts it into a visible image. A text editor does not understand the image format, so it cannot display the image properly.

    BINARY FILE IDEA
    Binary Data needs correct software Meaningful Output

    Text File vs Binary File: Main Differences

    Text files and binary files differ in how they store data, how they are read, how they are edited, and how they are used in real-world programs.

    Basis Text File Binary File
    Data Storage Stores data as readable characters. Stores data as raw bytes.
    Human Readability Usually human-readable. Usually not human-readable directly.
    Common Examples .txt, .csv, .json, .xml, .html, .log .jpg, .png, .mp3, .mp4, .pdf, .exe, .zip
    Editing Can usually be edited in a text editor. Needs special software or binary editor.
    Encoding Depends on character encoding such as UTF-8. Usually interpreted according to file format specifications.
    File Size May be larger for some structured data. Often more compact for complex data.
    Processing Processed as strings, lines, or characters. Processed as bytes or byte streams.
    Use Case Good for readable records, configuration, logs, and source code. Good for images, audio, video, executable files, and complex data.
    Portability Easy to inspect and transfer across systems. Portable if the correct software understands the format.
    Error Visibility Errors may be easier to identify by opening the file. Errors may be harder to inspect without special tools.

    Text Files and Character Encoding

    Text files store characters, but computers internally store everything as numbers or bytes. Character encoding defines how characters are converted into bytes and how bytes are converted back into characters.

    Common text encodings include:

    Encoding Description Common Use
    ASCII Supports basic English letters, digits, and symbols. Older simple text files.
    UTF-8 Supports many languages and symbols. Modern applications, web files, source code, JSON files.
    UTF-16 Uses more bytes for many characters. Some systems and applications.
    Important: If a text file is opened using the wrong encoding, some characters may appear incorrectly. UTF-8 is commonly used in modern programming.

    Binary Files and Bytes

    Binary files are usually handled as sequences of bytes. A byte is a small unit of data storage. Programs read and write binary files using byte-level operations instead of normal text operations.

    Binary files are useful when data should be stored exactly as bytes. This is important for images, audio, video, compressed files, encrypted files, and executable files.

    BINARY STORAGE
    Binary File = Byte + Byte + Byte

    A binary file may contain data such as:

    • Image pixel values
    • Audio samples
    • Video frames
    • Compressed data blocks
    • Program instructions
    • Database pages
    • Encrypted content

    Conceptual Reading Difference

    The way programs read text files and binary files is different. Text files are commonly read as strings or lines. Binary files are commonly read as bytes.

    Reading Text File

    • Open file in text mode.
    • Read content as characters or strings.
    • Process line by line if needed.
    • Use encoding such as UTF-8.

    Reading Binary File

    • Open file in binary mode.
    • Read content as bytes.
    • Interpret bytes according to file format.
    • Use suitable software or parser.
    
    // Conceptual text file reading
    
    open "students.txt" in text read mode
    read lines as text
    process each line
    close file
    
    
    // Conceptual binary file reading
    
    open "photo.jpg" in binary read mode
    read bytes
    interpret bytes as image data
    close file
    

    Conceptual Writing Difference

    Writing text files and binary files also works differently. Text files are written using strings, while binary files are written using bytes.

    
    // Conceptual text file writing
    
    open "students.txt" in text write mode
    write "Rahul"
    write "Ayesha"
    close file
    
    
    // Conceptual binary file writing
    
    open "image-copy.jpg" in binary write mode
    write byte data
    close file
    

    If you accidentally write binary data as text, the file may become corrupted. Similarly, if you treat a text file as binary, the program may still read bytes, but you will need to convert them correctly into characters.

    Java Example: Reading a Text File

    The following Java example reads a text file line by line. This is suitable for text files such as students.txt.

    Prerequisites: To understand this example, you should know Java classes, main method, strings, loops, exception handling, and basic file paths.
    
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
    
            String filePath = "students.txt";
    
            try {
                BufferedReader reader = new BufferedReader(new FileReader(filePath));
    
                String line;
    
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
    
                reader.close();
    
            } catch (IOException error) {
                System.out.println("Error reading text file: " + error.getMessage());
            }
        }
    }
    

    This example reads the file as text. Each line is handled as a string.

    Java Example: Reading a Binary File

    The following Java example reads a binary file as bytes. This is suitable for files such as images, PDFs, audio files, or other binary data.

    
    import java.io.FileInputStream;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
    
            String filePath = "photo.jpg";
    
            try {
                FileInputStream inputStream = new FileInputStream(filePath);
    
                int byteData;
    
                while ((byteData = inputStream.read()) != -1) {
                    System.out.println(byteData);
                }
    
                inputStream.close();
    
            } catch (IOException error) {
                System.out.println("Error reading binary file: " + error.getMessage());
            }
        }
    }
    

    This example reads the binary file byte by byte. The output will be numbers representing byte values, not meaningful text.

    JavaScript Example: Text File in Node.js

    In Node.js, a text file can be read using UTF-8 encoding so that the file content is returned as text.

    Prerequisites: To understand this example, you should know JavaScript variables, Node.js basics, callbacks, strings, and file reading.
    
    const fs = require("fs");
    
    const filePath = "students.txt";
    
    fs.readFile(filePath, "utf8", function(error, data) {
        if (error) {
            console.log("Error reading text file: " + error.message);
            return;
        }
    
        console.log(data);
    });
    

    Here, utf8 tells Node.js to interpret the file content as readable text.

    JavaScript Example: Binary File in Node.js

    If no text encoding is provided, Node.js can read file data as a buffer, which represents raw binary data.

    
    const fs = require("fs");
    
    const filePath = "photo.jpg";
    
    fs.readFile(filePath, function(error, data) {
        if (error) {
            console.log("Error reading binary file: " + error.message);
            return;
        }
    
        console.log(data);
    });
    

    In this example, data is a buffer containing bytes from the binary file.

    PHP Example: Text File

    PHP can read text files easily using file_get_contents().

    Prerequisites: To understand this example, you should know PHP variables, echo statement, file paths, and basic file reading.
    
    <?php
    
    $filePath = "students.txt";
    
    if (file_exists($filePath)) {
        $content = file_get_contents($filePath);
        echo $content;
    } else {
        echo "Text file not found.";
    }
    
    ?>
    

    This example reads the content as text and displays it.

    C# Example: Text File

    In C#, text files can be read using methods such as File.ReadAllText() or File.ReadAllLines().

    Prerequisites: To understand this example, you should know C# strings, classes, Main method, exception handling, and file paths.
    
    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            string filePath = "students.txt";
    
            try
            {
                string content = File.ReadAllText(filePath);
    
                Console.WriteLine(content);
            }
            catch (Exception error)
            {
                Console.WriteLine("Error reading text file: " + error.Message);
            }
        }
    }
    

    C# Example: Binary File

    Binary files in C# can be read using File.ReadAllBytes().

    
    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            string filePath = "photo.jpg";
    
            try
            {
                byte[] data = File.ReadAllBytes(filePath);
    
                Console.WriteLine("Total bytes read: " + data.Length);
            }
            catch (Exception error)
            {
                Console.WriteLine("Error reading binary file: " + error.Message);
            }
        }
    }
    

    This example reads the entire binary file into a byte array.

    Common Examples of Text and Binary Files

    The following table shows common file extensions and whether they are usually text-based or binary-based.

    File Extension File Type Text or Binary Common Use
    .txt Plain Text File Text Notes, simple records, plain content.
    .csv Comma-Separated Values Text Tabular records and spreadsheet data.
    .json JSON File Text Configuration, API data, structured records.
    .xml XML File Text Tag-based structured data.
    .html HTML File Text Web page markup.
    .jpg Image File Binary Photos and compressed images.
    .png Image File Binary Images with transparency support.
    .mp3 Audio File Binary Music and audio storage.
    .mp4 Video File Binary Video content.
    .pdf Portable Document File Binary Formatted documents.
    .exe Executable File Binary Runnable applications.
    .zip Compressed Archive Binary Compressed file collections.

    Advantages of Text Files

    Text files are widely used because they are simple, readable, and easy to work with. They are especially useful for beginner-level programming and small data storage tasks.

    Benefits of Text Files

    • Easy to read by humans.
    • Easy to edit using a normal text editor.
    • Useful for logs, configuration, and simple records.
    • Good for learning file handling basics.
    • Can be processed line by line.
    • Can store structured data using CSV, JSON, or XML.
    • Easy to debug because content can be opened and inspected.
    • Works well for source code and documentation files.
    • Useful for exchanging simple data between systems.
    • Often portable across different operating systems.

    Limitations of Text Files

    Text files are simple and useful, but they are not always the best choice for every type of data.

    Larger Size for Some Data Text representation can be larger than binary representation for some types of data.
    Slower for Complex Data Large text files may require parsing, which can be slower than reading optimized binary formats.
    Encoding Issues Text files may display incorrectly if the wrong encoding is used.
    Not Suitable for Media Data Images, audio, and video are not efficiently stored as plain text.

    Advantages of Binary Files

    Binary files are useful for storing complex data efficiently. They are commonly used in professional software systems, multimedia applications, databases, and compiled programs.

    Benefits of Binary Files

    • Efficient for storing complex data.
    • Often smaller than equivalent text representation.
    • Useful for images, audio, video, and executable files.
    • Can preserve exact byte-level data.
    • Good for performance-sensitive applications.
    • Useful for compressed and encrypted data.
    • Can store data in formats optimized for specific software.
    • Suitable for database and application-specific storage.
    • Better for non-text information.
    • Supports precise representation of binary structures.

    Limitations of Binary Files

    Binary files are powerful, but they are harder for beginners to inspect and edit directly.

    Not Human-Readable Binary files usually cannot be understood by opening them in a normal text editor.
    Needs Correct Software Binary files usually require specific applications or libraries to interpret them correctly.
    Harder to Debug It is more difficult to inspect binary data manually compared to text data.
    Corruption Risk Editing binary files incorrectly can easily corrupt them.
    Format Dependency Binary files often depend on a specific file format structure.

    When Should You Use Text Files?

    Text files are suitable when readability, simplicity, and easy editing are important. They are especially useful for beginner projects and simple data storage.

    Use Text Files When

    • You need human-readable content.
    • You are storing simple records.
    • You are creating logs.
    • You are saving configuration settings.
    • You are exporting CSV or JSON data.
    • You want easy debugging.
    • You are storing source code or markup.
    • You are working on beginner-level file handling projects.

    When Should You Use Binary Files?

    Binary files are suitable when data is complex, large, non-textual, or needs to be stored efficiently in a specific format.

    Use Binary Files When

    • You are storing images.
    • You are storing audio or video.
    • You are working with PDF or document formats.
    • You need compact storage.
    • You need exact byte-level data.
    • You are working with compressed files.
    • You are storing encrypted data.
    • You are working with executable files or database files.

    Real-World Example: Student Management System

    In a student management system, both text files and binary files may be used depending on the requirement.

    Requirement Suitable File Type Reason
    Store student names and marks Text file / CSV file Data is simple and readable.
    Store application logs Text file / Log file Logs should be easy to read and debug.
    Store course configuration JSON file Structured text format is easy to edit and read.
    Store student profile photo Binary image file Images are stored as binary data.
    Store generated PDF certificate Binary PDF file PDF uses a specialized document format.
    Store compressed backup Binary ZIP file Compressed archives are binary files.

    Safety Considerations

    Programs should handle text and binary files carefully. Reading a binary file as text or writing text data into a binary file incorrectly can produce errors or corrupt files.

    Safety Tips

    • Open text files in text mode when working with readable content.
    • Open binary files in binary mode when working with raw bytes.
    • Use correct encoding for text files.
    • Do not edit binary files in a normal text editor unless you know what you are doing.
    • Use proper libraries for images, PDFs, audio, and video files.
    • Validate file extensions and file formats before processing.
    • Keep backups before modifying important files.
    • Handle file reading and writing errors properly.

    Common Mistakes Beginners Make

    Beginners often confuse text files and binary files because both are stored on disk as data. However, the way they should be read and interpreted is different.

    Common Mistakes

    • Trying to read an image file as normal text.
    • Opening a binary file in a text editor and expecting readable content.
    • Ignoring character encoding in text files.
    • Writing binary data using text writing methods.
    • Assuming file extension always guarantees file format.
    • Editing binary files manually and corrupting them.
    • Using text mode when byte-level accuracy is required.
    • Not using proper libraries for binary formats.

    Better Approach

    • Use text mode for readable text files.
    • Use binary mode for images, PDFs, audio, video, and byte data.
    • Use UTF-8 encoding for modern text files when suitable.
    • Use proper file parsing libraries for structured formats.
    • Validate file type before processing.
    • Keep backups before modifying important files.
    • Understand the file format before reading or writing it.
    • Handle errors using exception handling.

    Debugging Text and Binary File Problems

    When a file does not open or display correctly, it is important to check whether the program is treating the file as the correct type.

    Debugging Checklist

    • Check whether the file is text-based or binary-based.
    • Check whether you are using the correct file mode.
    • Check whether the file extension matches the actual content.
    • Check whether the file path is correct.
    • Check whether the file is corrupted.
    • Check whether the correct encoding is used for text files.
    • Check whether a proper library is needed for binary files.
    • Try opening the file with the correct application.
    • Use small test files before working with large files.
    • Read error messages carefully.

    Mini Practice Activity

    Complete the following practice tasks to strengthen your understanding of text files and binary files.

    Task Description Expected Learning
    Task 1 Create a text file named students.txt and write three student names. Understand readable text file storage.
    Task 2 Open students.txt in a text editor and observe the content. Understand human readability of text files.
    Task 3 Open an image file in a text editor and observe the result. Understand that binary files are not directly readable.
    Task 4 Read a text file using text mode in any programming language. Practice text file reading.
    Task 5 Read an image file as bytes and print the total byte count. Understand binary file reading.
    Task 6 Create a table of common file extensions and classify them as text or binary. Improve file type recognition.

    Frequently Asked Questions

    1. What is a text file?

    A text file is a file that stores data as readable characters. It can usually be opened and understood using a normal text editor.

    2. What is a binary file?

    A binary file stores data as raw bytes. It usually requires specific software to interpret and display the content correctly.

    3. What is the main difference between text file and binary file?

    The main difference is that text files store readable character data, while binary files store raw byte data that is usually not directly readable by humans.

    4. Is a CSV file a text file?

    Yes. A CSV file is usually a text file because it stores data as readable characters separated by commas.

    5. Is a JSON file a text file?

    Yes. A JSON file is usually a text file because it stores structured data in readable key-value format.

    6. Is an image file a binary file?

    Yes. Image files such as JPG and PNG are binary files because they store image data as bytes.

    7. Can a binary file be opened in a text editor?

    It can be opened, but the content will usually appear as unreadable symbols or strange characters because the file is not stored as normal text.

    8. Why are binary files used?

    Binary files are used because they are efficient for storing complex data such as images, audio, video, compressed files, executable programs, and database files.

    9. Which file type is easier for beginners?

    Text files are easier for beginners because they are readable, simple to create, and easier to debug.

    10. Can a program convert text data into binary data?

    Yes. Programs can convert text into bytes using encoding such as UTF-8. Programs can also convert bytes back into text if the correct encoding is used.

    Summary

    Text files and binary files are two important file types in programming. A text file stores data as readable characters, while a binary file stores data as raw bytes. Both types are useful, but they are used for different purposes.

    Text files are best for readable data such as notes, logs, CSV records, JSON configuration, XML data, HTML files, and source code. Binary files are best for complex or non-text data such as images, audio, video, PDFs, executable files, compressed files, and database files.

    Beginners should understand when to use text mode and when to use binary mode. Using the wrong mode or wrong interpretation can produce incorrect output or corrupt files. Good file handling requires choosing the correct file type, using correct encoding, using proper file modes, and handling errors safely.

    Key Takeaway

    A text file stores readable character data, while a binary file stores raw byte data. Use text files for readable records, logs, CSV, JSON, and source code. Use binary files for images, audio, video, PDFs, compressed files, executable files, and other byte-based data.