C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
list with the altered list of letters.*/
#include <stdio.h>
#include <stdlib.h>
FILE * fptr;
main()
{
char letter;
int i;
fptr = fopen("C:\\users\\deanwork\\documents\\letters.txt", "r+");
if (fptr == 0)
{
printf("There was an error while opening the file.\n");
exit(1);
}
printf("Which # letter would you like to change (1-26)? ");
scanf(" %d", &i);
// Seeks that position from the beginning of the file
fseek(fptr, (i-1), SEEK_SET); // Subtract 1 from the position
// because array starts at 0
// Write an * over the letter in that position
fputc('*', fptr);
// Now jump back to the beginning of the array and print it out
fseek(fptr, 0, SEEK_SET);
printf("Here is the file now:\n");
for (i = 0; i < 26; i++)
{
letter = fgetc(fptr);
printf("The next letter is %c.\n", letter);
}
fclose(fptr); // Again, always close your files
return(0);
}

The program prints the contents of the file after the * is written at the position indicated by the user.
Here is a sample session:


The next letter is A.
The next letter is B.
The next letter is C.
The next letter is D.
The next letter is E.
The next letter is F.
The next letter is G.
The next letter is *.
The next letter is I.
The next letter is J.
The next letter is K.
Free download pdf