Exercise
Extract text from a binary file
Objetive
Create a program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The extracted characters should be those whose ASCII code is between 32 and 127, or equal to 10 or 13.
Example Code
// Import the necessary namespaces for file handling and basic input/output operations
using System;
using System.IO;
// Declare the main Program class
class Program
{
// Main method where the program starts
static void Main()
{
// Specify the input binary file and output text file paths
string inputFilePath = "input.bin"; // Replace with the path to your binary file
string outputFilePath = "output.txt"; // Replace with the desired output file path
// Try to process the binary file and extract printable characters
try
{
// Open the input binary file using a BinaryReader
using (BinaryReader reader = new BinaryReader(File.Open(inputFilePath, FileMode.Open)))
{
// Create a StreamWriter to write the extracted characters to the output file
using (StreamWriter writer = new StreamWriter(outputFilePath))
{
// Read the entire file byte by byte
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
// Read the next byte from the file
byte b = reader.ReadByte();
// Check if the byte represents an ASCII character between 32 and 127, or is 10 (newline) or 13 (carriage return)
if ((b >= 32 && b <= 127) || b == 10 || b == 13)
{
// Write the character to the output file
writer.Write((char)b);
}
}
}
}
// Notify the user that the extraction was successful
Console.WriteLine($"Extracted text has been saved to '{outputFilePath}'");
}
catch (Exception ex) // Catch any errors that may occur during file reading or writing
{
// Print the error message to the console
Console.WriteLine($"Error processing the file: {ex.Message}");
}
}
}