- 1 year ago
Reading from binary file LANG C
Comment
1 / 1
To read from a binary file in the C programming language, you can use the fread
function. Here's an example of how you can read data from a binary file:
c#include <stdio.h>
int main() {
FILE* file = fopen("binary_file.bin", "rb"); // Open the binary file in read mode
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Read data from the file
char buffer[100];
size_t elements_read = fread(buffer, sizeof(char), sizeof(buffer), file);
// Check if reading was successful
if (elements_read == 0) {
printf("Error reading the file.\n");
} else {
// Process the data here
// ...
printf("Data read: %s\n", buffer);
}
// Close the file
fclose(file);
return 0;
}
In this example:
- We use the
fopen
function to open the binary file in read mode by specifying"rb"
as the second parameter. - If the file fails to open, we print an error message and return with a non-zero exit code.
- We define a buffer to hold the data read from the file (
char buffer[100]
). - We use the
fread
function to read data from the file. It takes the buffer, element size, number of elements to read, and the file pointer as arguments. - The return value of
fread
is the number of elements successfully read. - If
fread
returns0
, it means there was an error reading the file. - Otherwise, we can process the data as needed. In this example, we simply print the data read from the file.
Remember to adjust the file name and path ("binary_file.bin"
) to match the actual binary file you want to read.
Make sure to handle any errors that may occur during file operations, such as failed file opening or reading.