gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Write an ANSI C function to read a binary file and return it as a character array. Try…
- User
Write an ANSI C function to read a binary file and return it as a character array. Try to make it fast.
- Assistant
Here's an ANSI C function that reads a binary file and returns its content as a character array:
#include <stdio.h> #include <stdlib.h> char* readBinaryFile(const char* filename, size_t* size) { FILE* file = fopen(filename, "rb"); if (file == NULL) { perror("Error opening file"); exit(1); } fseek(file, 0, SEEK_END); *size = ftell(file); fseek(file, 0, SEEK_SET); char* buffer = malloc(*size); if (buffer == NULL) { fclose(file); perror("Memory allocation error"); exit(1); } fread(buffer, 1, *size, file); fclose(file); return buffer; }This function takes the filename as an argument and a pointer to a
size_tvariable, which will hold the size of the file after the function executes.Here's how you can use the function to read a binary file and store its content in a character array:
int main() { const char* filename = "example.bin"; size_t size; char* buffer = readBinaryFile(filename, &size); // You can now access the file content through the 'buffer' variable free(buffer); // Don't forget to free the memory after you're done using it return 0; }