QUESTION:The following program reads from a text file containing numeric data stored in columns separated by one blank space. Write the code and compile it on your computer. Create a text file called myfile.txt containing a few columns (3×5 for example) of numeric data (real numbers) and test the program.
#include <stdio.h>
int main(void)
{
FILE *fp;
double val;
char ch;
fp = fopen("myfile.txt","r");
do{
fscanf( fp, "%lf", &val );
ch = getc(fp);
printf(" %lf",val);
if ( ch=='\n' || ch==EOF )
printf("\n");
} while ( ch != EOF );
fclose(fp);
return 0;
}
Analyse the code and include comment lines explaining how the program achieves its task. Modify the code so that the program additionally creates a new text file where it stores only the integer part (discard the factionary part) of the real numbers stored in myfile.txt. The new file should write data in the same format (3×5 with columns separated by space) as the original file. Include statements to check if the file was opened and closed successfully. Submit only the final, commented code.
Code:
#include <stdio.h>
int main(void)
{
FILE *fp,*fw;// declaring file pointers.
double val;
char ch;
int new;
if((fp = fopen("myfile.txt","r"))==NULL);
{
printf("sorry,cannot open the file\n");
exit(0);
}
fw = fopen("mynewfile.txt","w");
do{
fscanf(fp, "%lf", &val); //read real number from the file.
ch = getc(fp); //get the following number after the realnumber.
new=val;
fprintf(fw,"%d",new);
printf("%lf",val); //print out the real number.
printf("%d",new); //print out the integer number.
if ( ch=='\n' || ch==EOF )//determin to end the progress if there is a '\n' char or End Of File.
printf("\n"); // switch to next line.
}while ( ch != EOF );
fclose(fp);
return 0;
}
i am unsure how to get the integer part of real number.
10-2.c: In function ‘main’:
10-2.c:12: warning: incompatible implicit declaration of built-in function ‘exit’
the message return from compiler.