Exercise
Reading A Binay File (2 - GIF)
Objective
Create a C# program to check if a GIF image file seems to be correct.
It must see if the first four bytes are G, I, F, 8.
In case it seems correct, it must also display the GIF version (87 or 89), checking if the following byte is a 7 or a 9.
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces
using System; // Importing the System namespace for basic C# functionality
using System.IO; // Importing the IO namespace for file operations
public class GifFileChecker
{
// Method to check if the GIF file seems to be correct and to display the GIF version
public static void CheckGifFile(string fileName)
{
// Open the file in binary mode for reading
using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open))) // Use BinaryReader to read bytes from the file
{
// Read the first four bytes of the file to check the header
byte[] header = reader.ReadBytes(4); // Read the first 4 bytes
// Check if the first four bytes are G, I, F, and 8
if (header[0] == 0x47 && header[1] == 0x49 && header[2] == 0x46 && header[3] == 0x38) // Check if the bytes match "GIF8"
{
// Display that the file is a valid GIF file
Console.WriteLine("This is a valid GIF file.");
// Read the next byte to determine the GIF version
byte versionByte = reader.ReadByte(); // Read the next byte
// Check the version byte for 87 or 89
if (versionByte == 0x37) // If the byte is 0x37 (ASCII for "7"), it is GIF 87
{
Console.WriteLine("GIF Version: 87a"); // Display the GIF version
}
else if (versionByte == 0x39) // If the byte is 0x39 (ASCII for "9"), it is GIF 89
{
Console.WriteLine("GIF Version: 89a"); // Display the GIF version
}
else
{
Console.WriteLine("Unknown GIF version.");
}
}
else
{
// If the first four bytes don't match "GIF8", it's not a valid GIF file
Console.WriteLine("This is not a valid GIF file.");
}
}
}
}
class Program
{
// Main method where the program execution starts
static void Main(string[] args)
{
// Check if the user provided the file name as an argument
if (args.Length < 1) // If no file name is provided
{
Console.WriteLine("Please provide the GIF file name."); // Prompt user to provide the file
return; // Exit the program if no file is provided
}
string fileName = args[0]; // Assign the file name from the command line argument
// Check if the input file exists
if (!File.Exists(fileName)) // If the file doesn't exist
{
Console.WriteLine($"The file '{fileName}' does not exist."); // Print error message
return; // Exit the program if the file doesn't exist
}
// Call the method to check the GIF file
GifFileChecker.CheckGifFile(fileName); // Check the file and display the result
}
}