/*------------------------------------------------------------------*/ /* testtmpfile.c */ /* Demonstrate the tmpfile() function. */ /*------------------------------------------------------------------*/ #include #include int main(void) /* Demonstrate using the tmpfile() function to change the contents of a file. The program assumes that a file named "origfile" exists. Return 0. */ { FILE *psOrigFile; FILE *psTempFile; int iChar; /* Open the original file. */ psOrigFile = fopen("origfile", "r"); assert(psOrigFile != NULL); /* Open the temporary file. */ psTempFile = tmpfile(); assert(psTempFile != NULL); /* Copy all data from the original file to the temporary file. */ while ((iChar = getc(psOrigFile)) != EOF) putc(iChar, psTempFile); /* Write one more line to psTempFile. */ fprintf(psTempFile, "This is another line.\n"); /* Close the original file, and reopen it for writing. */ fclose(psOrigFile); psOrigFile = fopen("origfile", "w"); assert(psOrigFile != NULL); /* Move the temporary file's pointer to the beginning of the file. */ fseek(psTempFile, 0, SEEK_SET); /* Copy all data from the temporary file back to the original file. */ while ((iChar = getc(psTempFile)) != EOF) putc(iChar, psOrigFile); /* Close both files. */ fclose(psOrigFile); fclose(psTempFile); return 0; } /* Sample execution: $ gcc -Wall -ansi -pedantic -o testtmpfile testtmpfile.c $ cat origfile This is line one. This is line two. $ testtmpfile $ cat origfile This is line one. This is line two. This is another line. */