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Ä
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 :
Then you can reconstruct the integer with strtol function :
Now you can calculate the square of this number, and then use the previous array to convert the int result in char array :
And to finish, just write the result to the file :