Simple C program to load a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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