1 2 3 4 5 6

Example
The fgets() and fputs() functions could be used as follows:

#define MAX_LENGTH 256
char buffer[MAX_LENGTH];
FILE* fp = fopen("tally.data", "r"); FILE* fptr = fopen ("tally.out", "a");

while (fgets(buffer, MAX_LENGTH, fp) != NULL) {
/*read until EOF*/
/*process a line of the file*/
/*append tally.data to tally.out*/
fputs (buffer, fptr);
}
fclose (fp);
fclose (fptr);

*

We could also dyamically acquire memory for buffer[] as follows:

char* buffer;
buffer = (char*) malloc (MAX_LENGTH * sizeof (char));
Instead of close() we would use:
free(buffer);/* to give back the space*/ The companion special functions gets() and puts() that read/write stdin and stdout are best forgotten.

*

*

1 February, 1998

5

CopyrightUniversity of Alberta