QP School

Full Version: Text and binary files in C
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
C supports both text and binary file handling.

// Writing to a binary file
int data[] = {10, 20, 30, 40, 50};
FILE *binary_file = fopen("data.bin", "wb");
if (binary_file != NULL) {
    fwrite(data, sizeof(int), 5, binary_file);
    fclose(binary_file);
}

// Reading from a binary file
int read_data[5];
binary_file = fopen("data.bin", "rb");
if (binary_file != NULL) {
    fread(read_data, sizeof(int), 5, binary_file);
    fclose(binary_file);
    for (int i = 0; i < 5; i++) {
        printf("%d ", read_data[i]); // Output: 10 20 30 40 50
    }
}
printf("\n");