// file: lecture_15/example.cc // // local include files // #include "example.h" // my main program starts here // int main(int argc, char** argv) { // open the file // FILE* fp = fopen(argv[1], "r"); if (fp == (FILE*)NULL) { fprintf(stdout, "%s: error opening file (%s)\n", argv[0], argv[1]); } // declare a buffer to hold one line of data // char str[MAX_LINE_LEN]; // compute the number of lines in the file // long nlines = 0; while (fgets(str, MAX_LINE_LEN - 1, fp) != (char*)NULL) { nlines++; } fprintf(stdout, "the number of lines in %s is %d\n", argv[1], nlines); // rewind the file so we can read from it again // rewind(fp); // declare a data structure to hold the file // // char** mstr; // mstr = new char*[nlines]; // char* mstr[nlines]; // loop over all lines in the file // long linenum = 0; while (fgets(str, MAX_LINE_LEN - 1, fp) != (char*)NULL) { // allocate space: strip the newline character and adjust the length // of the string by decreasing it by one character // long len = strlen(str); str[len - 1] = (char)NULL; len--; // allocate space to hold the line - remember to allocate space for // the null character // mstr[linenum] = new char[len + 1]; // copy the data // strcpy(mstr[linenum], str); // increment the line number // linenum++; } // close the file // fclose(fp); // print the file // for (long i = 0; i < nlines; i++) { fprintf(stdout, "%d: %s\n", i, mstr[i]); } // deallocate memory // while (nlines > 0) { nlines--; delete [] mstr[nlines]; } // delete [] mstr; // exit gracefully // return 0; }