Search⌘ K
AI Features

Solution: File Reading and Writing

Learn how to read fruit names from a file and write their reversed versions to another file in C. Explore using file pointers, opening files with correct modes, checking for errors, processing strings, and safely closing file streams to manage input and output efficiently.

We'll cover the following...
C
#include <stdio.h>
int main(void)
{
FILE *fp; // Pointer to the file to be read
FILE* fout; // Pointer to the file to be written
int numfruits = 12; // There are 12 fruits listed in fruits.txt
char myFruits[numfruits][256]; // Each fruit name has a length smaller than 256
char myFruitsReversed[numfruits][256];
int i, j; // Needed for looping
int indexEnd, count; // Needed for reversing strings
// Open both files in the appropriate read or write mode
fp = fopen("fruits.txt", "r");
fout = fopen("output/outfile.txt", "w");
// Exit if there's an error opening either of the files
if (fp == NULL)
{
printf("There was an error opening fruits.txt\n");
return 1;
}
else if (fout == NULL)
{
printf("There was an error opening the file output/outfile.txt\n");
return 1;
}
else
{
// Loop and on step i, read the i^th string into the array
i = 0;
while (!feof(fp))
{
fscanf(fp, "%s\n", &myFruits[i]);
i++;
}
// For each string, find its size, reverse it and write it out
for(i = 0; i < numfruits; i++)
{
// Count the number of characters in the string
j = 0;
count = 0;
while(myFruits[i][j] != 0)
{
count++;
j++;
}
// Reverse the i^th string that was read
j = 0;
indexEnd = count - 1;
while(j < count)
{
myFruitsReversed[i][j] = myFruits[i][indexEnd];
j++;
indexEnd--;
}
//Insert a null character at the end of the reversed string
myFruitsReversed[i][j]='\0';
// Write out the reversed string
fprintf(fout, "%s \n", myFruitsReversed[i]);
}
// Close both file streams
fclose(fp);
fclose(fout);
}
return 0;
}
...