0

Okay, so i have a lot of problems with file handling and strings in C. The point of this task is to reverse the string from the output and to convert lower letters to upper and vice-versa. For example i have to get an output of ENALPOREa from an Aeroplane. I have to have 2 files. An input file where i have written Aeroplane and an output file where i have got ENALPOREa. Any help is appreciated !

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void inputOfAString(const char*nameOfTheFile){
FILE *fin = fopen(nameOfTheFile,"w");

if(fin == NULL){
   printf("Error");
   exit(1);
}

char s[20];
fgets(s,20,stdin);
fprintf(fin,"%s",s);

fclose(fin);
}


void readTheString(const char *inputOfTheFile,const char*outputOfTheFile){
   FILE *fout = fopen(outputOfTheFile,"w");
   FILE *fin = fopen(inputOfTheFile,"r");
   if(fout == NULL || fin == NULL){
       printf("Error");
       exit(1);
   }
   char s[20];
   while(!feof(fin)){
       fgets(s,20,inputOfTheFile);
       for(int i = 0;i<20;i++){
           if(s[i] == isupper(s[i])){
               s[i] = tolower(s[i]);
           }else{
               s[i] = tolower(s[i]);
           }
       }
       fputs(s,fout);
   }

   fclose(fout);
   fclose(fin);
}

int main(){
   inputOfAnString("input1.txt");
   readTheString("input1.txt","output1.txt");
   return 0;
}


1 Answers1

0

Test the result of fgets(), not feof().
(Whatever text or instructor suggested feof() - treat with suspicion).

Use the result of isupper() as T/F test.

One branch should use toupper()

Iterate to the end of the string, which may be less than 20.

   char s[20];
   //while(!feof(fin)){
   //    fgets(s,20,inputOfTheFile);
   while(fgets(s, sizeof s, inputOfTheFile)) {
       // for(int i = 0; i < 20;i++){
       for(int i = 0; s[i];i++){
           // if(s[i] == isupper(s[i])){
           if(isupper(s[i])){
               s[i] = tolower(s[i]);
           }else{
               //s[i] = tolower(s[i]);
               s[i] = toupper(s[i]);
           }
       }
       fputs(s,fout);
   }

Advanced: use unsigned char for avoid calling is...(), to...() with negative values.

Tight alternative

   #define S_SIZE 20
   char s[S_SIZE];
   while (fgets(s, sizeof s, inputOfTheFile)) {
       const unsigned char *p = (const unsigned char *) s;
       while (*p) {
           if(isupper(*p)) {
               *p = tolower(*p);
           } else {
               *p = toupper(*p);
           }
           p++;
       }
       fputs(s, fout);
   }
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256