Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * readfile.c
- *
- * Demonstration on how to get filesize of a given file,
- * open it and print it to console, using C standard library
- *
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- long int size = 0;
- char *content;
- char* readFile(char* filename)
- {
- FILE* file = fopen(filename,"r");
- if(file == NULL)
- {
- return NULL;
- }
- fseek(file, 0, SEEK_END);
- size = ftell(file);
- rewind(file);
- content = calloc(size + 1, 1);
- fread(content,1,size,file);
- return content;
- }
- int main(int argc,char **argv)
- {
- FILE *file;
- char *myfile = calloc(256, sizeof(char));
- if(myfile)
- {
- /* get filesize */
- file = fopen("readfile.c", "r");
- fseek(file, 0, SEEK_END);
- size = ftell(file);
- rewind(file);
- fclose(file);
- printf("File size: %ld\n", size);
- /* get some extra RAM...*/
- myfile = realloc(myfile, sizeof(char) * 8);
- /* get file content */
- myfile = readFile("readfile.c");
- /* output file content */
- printf("%s", myfile);
- printf("\nTime to leave!\n\n");
- /* Free memory and exit */
- //free(content);
- free(myfile);
- return EXIT_SUCCESS;
- }
- /* if calloc() has failed... */
- return EXIT_FAILURE;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement