Created
July 30, 2015 18:28
-
-
Save rmccullagh/b0ad67bbc403279955ef to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
#include <stdio.h> | |
#include <sys/stat.h> | |
/* | |
* memory allocation sub routine that DOES NOT fail | |
*/ | |
void* tryAllocate() | |
{ | |
void* buffer; | |
while((buffer = malloc(10)) == NULL) | |
sleep(1); | |
return buffer; | |
} | |
int main(int argc, char** argv) | |
{ | |
if(argc != 2) { | |
printf("Usage: %s <FILE>\n", argv[0]); | |
return 1; | |
} | |
struct stat st; | |
if(stat(argv[1], &st) < 0) { | |
printf("error: error reading file\n"); | |
return 1; | |
} | |
char* buffer; | |
buffer = malloc(st.st_size + 1); | |
if(!buffer) { | |
printf("error: error allocating memory\n"); | |
return 1; | |
} | |
FILE* fp = fopen(argv[1], "r"); | |
if(!fp) { | |
free(buffer); | |
printf("error opening file\n"); | |
return 1; | |
} | |
fread(buffer, st.st_size, 1, fp); | |
fclose(fp); | |
buffer[st.st_size] = '\0'; | |
printf("%s", buffer); | |
free(buffer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment