Skip to content

Instantly share code, notes, and snippets.

@lemire
Created March 6, 2021 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lemire/b2ef735747a4b1acebcfb47cb81dbe21 to your computer and use it in GitHub Desktop.
Save lemire/b2ef735747a4b1acebcfb47cb81dbe21 to your computer and use it in GitHub Desktop.
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