#include #include typedef int *RowType; void printPicture(RowType picture[], int numRows, int numCols ); void printToFile(FILE *fp, RowType picture[], int numRows, int numCols, int maxPixel ); int main() { FILE *fp, *fp2; char str[81]; char ch; int count=0; int comment; char *seps = " ,\n"; //"token" separators in a string int i; char *pch; // pointer to a character int numCols, numRows, maxPixel, pixel; int row, col; RowType *picture, oneRow; if ((fp = fopen("widget.pgm", "r")) == NULL) { printf("Error opening file to read\n"); exit (0); } if ((fp2 = fopen("newWidget.pgm", "w")) == NULL) { printf("Error opening file to write\n"); exit (0); } fgets(str, 80, fp); //read initial "P2" header line printf("%s", str); //echo print for debugging fgets(str, 80, fp); // check if this is a comment line printf("%s", str); //echo print for debugging if (str[0] == '#') comment = 1; else comment = 0; while (comment) { fgets(str, 80, fp); printf("%s", str); //echo print for debugging if (str[0] == '#') comment = 1; else comment = 0; } // strtok: breaks a string into "tokens" i = 0; pch = strtok( str, seps ) ; /* Find first token */ while( pch != NULL ) { if (i == 0) numCols = atoi(pch); if (i == 1) numRows = atoi(pch); printf( "Token %d: %s\n", ++i, pch ); pch = strtok( NULL, seps ); /* Find next token */ } // Check what has become of 'str'? printf( "str is now '%s', numCols = % d, numRows = %d\n", str, numCols, numRows ); /* THIS CODE READS A FILE LINE BY LINE UNTIL EOF, EACH LINE IS A STRING "STR": while (fgets(str, 80, fp) && count<5) //fgets() reads the end-of-line character \n { printf("%s", str); count++; } */ /* THIS CODE READS NUMBERS FROM A FILE OF UNKNOWN LENGTH UNTIL EOF: while (fscanf(fp, "%d", &pixel) != EOF) { printf("%5d", pixel); count++; if (count % 15 == 0) printf("\n"); } printf("\n"); */ fscanf(fp, "%d", &maxPixel); printf("Max Pixel value: %d\n", maxPixel); picture = (int **)malloc(sizeof(int*)*numRows); for (i=0; i< numRows; i++) picture[i] = (int *)malloc(sizeof(int)*numCols); for (row=0; row < numRows; row++) { for (col=0; col < numCols; col++) { fscanf(fp, "%d", &pixel); picture[row][col] = pixel; } } //echo print the picture matrix: printPicture(picture, numRows, numCols); printToFile(fp2, picture, numRows, numCols, maxPixel); return 0; } void printPicture(RowType picture[], int numRows, int numCols ) { int row, col; for (row=0; row < numRows; row++) { for (col=0; col < numCols; col++) { printf("%4d", picture[row][col]); if (col % 15 == 14) printf("\n"); } printf("\n"); } } void printToFile(FILE *fp, RowType picture[], int numRows, int numCols, int maxPixel ) { int row, col; fprintf(fp, "P2\n"); fprintf(fp, "#New PGM file with image shifted\n"); fprintf(fp, "%d %d\n%d\n", numCols, numRows, maxPixel); for (row=0; row < numRows; row++) { for (col=0; col < numCols; col++) { fprintf(fp, "%4d", picture[row][col]); if (col % 15 == 14) fprintf(fp, "\n"); } fprintf(fp, "\n"); } fclose(fp); }