/** * As with reader2, but breaking up and doing a double read of the file * so that the memory used to store the text is exactly the size of the * text itself. * * @author gtowell * Created March 2021 * * **/ #include #include #include /** * Count the numer of lines in the named file * @param the file to be counted * @return the numer of tlines in the line * **/ 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 and return a pointer to the 2d array * @param filename -- the name of the file to be read * @param linecount -- the number of lines in the file * @return a pointer to the read in information * **/ 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[]) { FILE* f = fopen(argv[1], "r"); if (!f) { fprintf(stderr, "No such file\n"); return 1; } fclose(f); int linecount = linecounter(argv[1]); char** text = readfile(argv[1], linecount); for (int i=0; i