Write a program to take 10 integers from the file and write the square of these integers into another file
C Program
#include <stdio.h>int main(){FILE *readFile;int num;char buffer[32] = {0};// creating a FILE pointerFILE *fptrWrite;// open the file in write modefptrWrite = fopen("square.txt", "w");if (fptrWrite != NULL){printf("File created successfully!\n");}else{printf("Failed to create the file.\n");// exit status for OS that an error occurredreturn -1;}readFile = fopen("hello.txt", "r");if (readFile == NULL){printf("Can't open file for integers.txt file.\n");return -1;}else{int count = 0;printf("\nRead Numbers from file:\n");while (!feof(readFile)){fscanf(readFile, "%d", &num);sprintf(buffer, "%d\n", num * num);fputs(buffer, fptrWrite);count++;if (count == 10){break;}}printf("\nEnd of file.\n");//close filesfclose(readFile);fclose(fptrWrite);}return 0;}
Input File: hello.txt
12 23 45 22 6 7 8 90 23 56 10 100
Output File: square.txt
144 529 2025 484 36 49 64 8100 529 3136
Output:
File created successfully!
Read Numbers from file:
End of file.
No comments:
Post a Comment