Чтение двоичных файлов в Linux: примеры кода на C, Python и Bash

Чтобы прочитать двоичный файл в Linux, вы можете использовать различные языки программирования и методы. Вот несколько примеров использования разных языков программирования:

  1. Язык C:

    #include <stdio.h>
    int main() {
    FILE *file = fopen("binaryfile.bin", "rb");
    if (file == NULL) {
        printf("Failed to open the file.");
        return 1;
    }
    // Seek to the end of the file to get its size
    fseek(file, 0, SEEK_END);
    long fileSize = ftell(file);
    // Seek back to the beginning of the file
    fseek(file, 0, SEEK_SET);
    // Read the entire file into a buffer
    char *buffer = malloc(fileSize);
    fread(buffer, 1, fileSize, file);
    // Process the file data as needed
    // Remember to free the allocated memory and close the file
    free(buffer);
    fclose(file);
    return 0;
    }
  2. Python:

    with open('binaryfile.bin', 'rb') as file:
    data = file.read()
    # Process the file data as needed
  3. Bash:

    #!/bin/bash
    file="binaryfile.bin"
    while IFS= read -r -n1 char; do
    # Process each character in the binary file as needed
    printf "%s" "$char"
    done < "$file"

Эти примеры демонстрируют чтение двоичного файла с использованием C, Python и Bash. Не забудьте заменить "binaryfile.bin"фактическим путем к вашему двоичному файлу.