#include #include #include /*** * Read a file into an array that is exactly the right length, and in which each line * is stored in a character array of exactly the right length. * Doing so requires two passes through the file. Pass 1 to count the lines. Pass 2 * to actually store **/ /** * Count the lines in a file * Note that in main I checked for file existence, so I do not need to do it here **/ int linecounter(char* filename) { FILE* f = fopen(filename, "r"); char line[256]; int linecount=0; while (fgets(line, 256, f)) { linecount++; } fclose(f); return linecount; } /** * Read the file into dynamically allocated array of dynamically allocated arrays * Hence, the char** **/ char** readfile(char* filename, int linecount) { char** rtn = malloc(linecount * sizeof(char*)); int lc=0; FILE* f = fopen(filename, "r"); char line[256]; while (fgets(line, 256, f)) { int llen = strlen(line); char* nline = malloc((llen+1)*sizeof(char)); strcpy(nline, line); rtn[lc++]=nline; } fclose(f); return rtn; } int main(int argc, char* argv[]) { // make sure the file really exists FILE* f = fopen(argv[1], "r"); if (!f) { fprintf(stderr, "No such file\n"); return 1; } fclose(f); //get the number of lines and read the file. //Yes, this could be written in one line // except that I need the line count later int linecount = linecounter(argv[1]); char** text = readfile(argv[1], linecount); // print the file for (int i=0; i