I need to copy the contents of a text file into a dynamically allocated array of characters.
My problem is getting the size of the contents of the file; Google shows that I need to use fseek and ftell , but for this, the file, apparently, needs to be opened in binary mode, and this only gives garbage.
EDIT: I tried to open text mode, but I get weird numbers. Here's the code (I skipped a simple error check for clarity):
long f_size; char* code; size_t code_s, result; FILE* fp = fopen(argv[0], "r"); fseek(fp, 0, SEEK_END); f_size = ftell(fp); fseek(fp, 0, SEEK_SET); code_s = sizeof(char) * f_size; code = malloc(code_s); result = fread(code, 1, f_size, fp);
source share