Here is my full code:
// Write a program that reads twelve strings from fruits.txt,
// reverses each string and outputs them to output/outfile.txt.
#include <stdio.h>
#include <string.h>
void main() {
FILE *fruitFile;
FILE *outputFile;
char fruit[32];
char revFruit[32];
fruitFile = fopen( "fruits.txt", "r" );
outputFile = fopen( "output.txt", "w" );
if (fruitFile == NULL) {
printf("there was an error opening fruits.txt\n");
} else if (outputFile == NULL) {
printf("there was an error opening output.txt\n");
} else {
while(!feof(fruitFile)) {
int j = 0;
size_t i = 0;
for (i = 0; i < strlen(revFruit); i++) {
revFruit[i] = '\0';
fruit[i] = '\0';
}
fscanf(fruitFile, "%s\n", &fruit);
for (i = strlen(fruit) - 1; i >= 0; i--) {
revFruit[j] = fruit[i];
if(i == 0) break;
j++;
}
printf("%s\n", revFruit);
fprintf(outputFile, "%s\n", revFruit);
}
fclose(fruitFile);
fclose(outputFile);
}
}
It is supposed to read from fruits.txt and write the fruits in reverse into output.txt, everything works fine but for some reason once a word is bigger than the others it messes up the whole revFruit string:
Test Input:
apple
mango
banana
grapes
pomegranate
blueberry
guava
apricot
cherry
orange
peach
pear
Test Output:
elppa
ognam
ananab
separg
etanargemop��
yrrebeulbop��
avaugeulbop��
tocirpalbop��
yrrehcalbop��
egnaroalbop��
hcaepoalbop��
raeppoalbop��
Which doesn't make sense to me. I am clearing both strings and I even tried printing revFruit it is empty right before the for loop, but once inside it has leftovers from the last fruit. I am new to C and kind of a noob so any explanation appreciated!