Skip to content

Instantly share code, notes, and snippets.

@lemire
Created Mar 6, 2021
Embed
What would you like to do?
Simple C program to load a file
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if (argc < 2) {
perror("provide a file argument");
}
FILE *pFile = fopen(argv[1], "rb");
if (pFile == NULL)
perror("Error opening file");
else {
if (fseek(pFile, 0, SEEK_END) < 0) {
perror("cannot seek the end of the file");
if (fclose(pFile) != 0) {
perror("can't close");
}
return EXIT_FAILURE;
} else {
long size = ftell(pFile);
printf("Size of %s: %ld bytes.\n", argv[1], size);
rewind(pFile);
char *buffer = (char *)malloc(size);
if (buffer == NULL) {
perror("can't allocate");
} else {
size_t bytes_read = fread(buffer, 1, size, pFile);
printf("Read: %zu bytes.\n", bytes_read);
free(buffer);
}
if (fclose(pFile) != 0) {
perror("can't close");
return EXIT_FAILURE;
}
}
}
printf("Completed succesfully\n");
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment