Why output is not as expected while running this following File Handling C Program?

58 Views Asked by At

This is a code to perform square of a number by taking input from one file and giving output in another file.

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

void main() {
   FILE *fp1, *fp2;
   char ch;
   fp1 = fopen("new.txt", "w");
   fputs("This is the new file 12",fp1);
   fclose(fp1);
   fp1 = fopen("new.txt", "r");
   fp2 = fopen("new1.txt", "w");

   while ((ch=fgetc(fp1))!=EOF)
   {
         if(isdigit(ch))
         {
            fputc((int)(ch*ch), fp2);
         }

   }

   printf("File copied Successfully!");
   fclose(fp1);
   fclose(fp2);
}

Expected content of new1.txt is 144

Actual content of new1.txt file is aÄ

1

There are 1 best solutions below

0
On

the way you do it is wrong. You aren't multiplying the entire number together. So you need first to find the entire number in the file. An easy way is to store all char in an array and keep the length aswell :

 while ((ch=fgetc(fp1))!=EOF)
 {
    if(isdigit(ch))
    {
        storeDigit[gotDigit] = ch;  // keep ref
        gotDigit += 1; // keep length       
    }
 }

Then you can reconstruct the integer with strtol function :

int digit = (int) strtol(storeDigit, NULL, 10);

Now you can calculate the square of this number, and then use the previous array to convert the int result in char array :

digit = digit * digit;
sprintf(storeDigit, "%d", digit);

And to finish, just write the result to the file :

int i = 0;
while(storeDigit[i] != '\0')
{
    fputc(storeDigit[i], fp2);
    i++;
}