exit(1);
}
for (letter = 'A'; letter <= 'Z'; letter++)
{
fputc(letter, fptr);
}
puts("Just wrote the letters A through Z");
// Now read the file backwards
fseek(fptr, -1, SEEK_END); // Minus 1 byte from the end
printf("Here is the file backwards:\n");
for (i = 26; i > 0; i--)
{
letter = fgetc(fptr);
// Reads a letter, then backs up 2
fseek(fptr, -2, SEEK_CUR);
printf("The next letter is %c.\n", letter);
}
fclose(fptr); // Again, always close your files
return(0);
}
Tip
As you can see, fputc() is a great function for outputting individual characters to a
file. fgetc() reads individual characters from a file. fputc() and fgetc() are
to putc() and getc() what fputs() and fgets() are to puts() and
gets().
So far, you might not see a purpose for random-access files. Random access offers you the advantage
of writing data to a file and then rereading the same data without closing and opening the file. Also,
fseek() lets you position the file pointer any number of bytes from the beginning, middle, or end of
the file.
Assuming that the file of letters still resides on the disk from the last program, this next program asks
the user which position he or she wants to change. The program then positions the file pointer with
fseek() and writes an * at that point before using fseek() to return to the beginning of the file
and printing it again.
Click here to view code image
// Example program #2 from Chapter 29 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter29ex2.c
/* The program opens the file created in the first program of the
chapter and changes one of the letters to an *. It then prints the new