Working with
Text and Binary Files



Introduction to File I/O

File I/O (Input/Output) is a fundamental concept in programming. It allows programs to interact with files stored on disk—either by reading data from them or writing data into them. Files are usually categorized as either text files or binary files.

Text vs Binary Files

Working with Text Files

Let’s start with reading and writing text files. This is the most common form of file I/O for logs, reports, config files, etc.

Example 1: Writing to a Text File

// Pseudocode to write lines into a text file
OPEN file "report.txt" in write mode
WRITE "Report for Q1" to file
WRITE "Total Sales: $45000" to file
CLOSE file

Output:

report.txt
-------------
Report for Q1
Total Sales: $45000

Question:

What happens if we open the file in write mode again?

Answer: The file will be overwritten. Any existing content will be erased.

Example 2: Reading from a Text File

// Pseudocode to read a text file line by line
OPEN file "report.txt" in read mode
WHILE not end of file
    READ line from file
    DISPLAY line
END WHILE
CLOSE file

Output:

Report for Q1
Total Sales: $45000

Working with Binary Files

Binary files store data in its raw format. They are often used for images, compiled code, audio, or structured data.

Example 3: Writing to a Binary File

// Pseudocode to write integers to a binary file
OPEN file "data.bin" in binary write mode
WRITE integer 1234 to file
WRITE integer 5678 to file
CLOSE file

Example 4: Reading from a Binary File

// Pseudocode to read integers from a binary file
OPEN file "data.bin" in binary read mode
READ integer from file and store in variable a
READ next integer and store in variable b
DISPLAY a, b
CLOSE file

Output:

1234
5678

Question:

Can we open a binary file in a text editor and still read it?

Answer: No. Binary files contain raw bytes which may not map to valid text characters. They can appear as gibberish or corrupt content in text editors.

Best Practices

Conclusion

Mastering file I/O helps in building real-world applications that store and retrieve data persistently. Understanding the difference between text and binary formats enables better decision-making when dealing with file storage and processing.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M