// file: my first program // #include #include #include #define MAX_LEN 9999 // my main program starts here // int main(int argc, char** argv) { // declare a buffer to hold one line of data // char str[MAX_LEN]; // 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]); } // compute the number of lines in the file // long nlines = 0; while (fgets(str, MAX_LEN - 1, fp) != (char*)NULL) { nlines++; } rewind(fp); // declare a data structure to hold the file // // char* mstr[nlines]; char** mstr; mstr = new char*[nlines]; // loop over all lines in the file // long linenum = 0; while (fgets(str, MAX_LEN - 1, fp) != (char*)NULL) { // allocate space // long len = strlen(str); str[len - 1] = (char)NULL; len--; 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 < linenum; i++) { fprintf(stdout, "%d: %s\n", i, mstr[i]); } // deallocate memory // while (nlines > 0) { delete [] mstr[nlines - 1]; nlines--; } delete [] mstr; // exit gracefully // return 0; }