So if I have a file with several numbers, and I open the file using
fp = fopen (filename, "r");
So now I can read the contents of the file correct? How could I do something with the file. Like in this file there are numbers and I want to be able to add them up.
fscanf(fp)
would be the beginning of what is supposed to be correct? But I am not sure what to do beyond it. What code represents the items inside the file I am opening? If it is “x” then I want to add all the “x”‘s up and then divide it by the total number of files there are.
How can I use the variables inside a file and do things with them?
Edited code:
if (fp != NULL)
{
while (fscanf(fp, "%lf", &d) == 1)
sum += d;
mean = sum / total;
printf ("The number of data values read from this file was %.0lf\n", total);
printf ("\n%.2lf\n", mean);
fclose(fp);
}
if (fp != NULL)
{
do
{
c = fgetc(fp);
if (c != EOF)
{
if ((char)c == '\n')
total++;
}
} while (feof(fp) == 0);
If the only content in the file is valid numbers, this will work. Actually, it will work until the first text that isn’t a valid number:
As a general rule, if a function opens a file successfully, it should close it when it’s finished. In this example, the system would close the file anyway, but it is as well to get into good habits. With a little more care and attention, you could distinguish between a format error (return value of 0 from
fscanf()) and EOF or I/O error.