// fread example: read an entire file // source: http://www.cplusplus.com/ // Class: this is an important snippet of code. // In crawler you will have to read a file into // a dynamically allocated (malloc) buffer. // Ponder: how big should the buffer be? Well, // at least as big as the file. How do you find // out how big the file is? Also, remember a // memory string has to be terminated by a NULL. // A file is terminated with EOF and not a NULL. // How do you make sure that a text file copied in // to a memory string terminates correctly? // CLASS: that's really important. // This little snippet answers those questions. #include #include #include int main() { FILE *pFile; long lSize; char *buffer; size_t result; pFile = fopen("myfile.txt", "r"); if (pFile==NULL){ fputs("File error\n", stderr); exit (1); } // obtain file size fseek(pFile, 0, SEEK_END); // seek to the end of the file lSize = ftell(pFile); // get the current file pointer rewind(pFile); // rewind to the beginning of the file // allocate memory to contain the whole file: // add one more byte for the NULL character to // terminate the memory string buffer = (char *)malloc(sizeof(char)*lSize + 1); if (buffer == NULL) { fputs("Memory error", stderr); exit (2); // different error code from the earlier // failed to open the file - why? } // set the memory to zero before you copy in. // the lSize + 1 byte will be 0 which is NULL '\0' // note, we clear memory and add the NULL at the same time memset(buffer, 0, sizeof(char)*lSize + 1); // copy the file into the buffer: result = fread(buffer, sizeof(char), lSize, pFile); if (result != lSize) { fputs("Reading error", stderr); exit (3); // we use different exit codes for different errrors, that's why. } // the whole file is now loaded in the memory buffer. Is it correct? // // look at the file using the cat myfile.txt. Problem is you // can't see hidden whitespace characters like newline or NULL. // try, od -t c myfile.txt. Now you can see the complete // file. What is at the end of the file? Probably a \n (newline). // Why not run gdb and look at the buffer contents. // Looks good. OK. // Let's print it out fputs(buffer, stdout); // terminate fclose(pFile); free(buffer); return EXIT_SUCCESS; }