Files,question about data
Hi!!!!I have a question...How can I use the data from a file????For example at the following code I want to write a function that finds the max of the numbers i*n,that exist in the file "d.dat".How can I do this????Thank you!!!
#include <stdio.h>
int main()
{
FILE *fp;
int i,n;
fp = fopen("d.dat","w");
if (fp==NULL) {
exit(0);
}
for (i=0; i<=10; i++){
printf("Give number:");
scanf("%d",&n);
fprintf(fp,"%d,%d\n",n,i*n);
}
fclose(fp);
return 0;
}
Re: Files,question about data
If you want to read data from a file using the FILE set of functions, then you need to open the file for reading.
Code:
fp = fopen("d.dat", "r");
Then assuming the file contains numbers in the format n,n then you can read the numbers using
Code:
fscanf(fp, "%d,%d", &n, &in);
You loop on fscanf until it returns EOF to indicate that all the numbers have been read.
This gives the program to input the numbers, create the file, read and display from the file and print the largest i*n number as
Code:
#include <stdio.h>
int main()
{
FILE *fp;
int i,
n,
in,
max = -999999999;
if ((fp = fopen("d.dat", "w")) == NULL)
return 1;
for (i = 0; i <= 10; i++){
printf("Give number:");
scanf("%d", &n);
fprintf(fp, "%d,%d\n" ,n, i * n);
}
fclose(fp);
if ((fp = fopen("d.dat", "r")) == NULL)
return 2;
while (fscanf(fp, "%d,%d", &n, &in) != EOF) {
printf("n is %d, in is %d\n", n, in);
if (in > max)
max = in;
}
printf("The largest i*n is %d\n", max);
fclose(fp);
return 0;
}
Re: Files,question about data
Thank you very much...!!!!!!