Reputation: 1
I am attempting to complete a lab. When I run this code nothing is written to the text file that is created. According to the lab it should write A thru Z to the text file.
//Example program #1. Chapter 29
// File Chapter29exl.c
/* The program open a file named letters.txt and prints A through Z in the file.
It then loops backward through the file printing each of the letters from z to A. */
#include <stdio.h>
#include <stdlib.h>
FILE * fptr;
main()
{
char letter;
int i;
fptr = fopen("letters.txt", "w+");
if (fptr == 0)
{
printf(" There was an error while opening the file.\n");
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, leeter");
}
fclose(fptr);
return(0);
}
The code created the file but it is blank. Thanks
Upvotes: 0
Views: 53
Reputation: 20745
In line, you're not passing the variable for %c
, only a string
printf("The next letter is %c/\n, leeter");
It should be:
printf("The next letter is %c/\n", letter);
You can detect this easily if you look at the compiler warnings. By default, GCC produces the following warning for your code:
warning: format '%c' expects a matching 'int' argument [-Wformat=]
printf("The next letter is %c/\n, leeter");
Indicating the argument is missing.
Upvotes: 1