Now that you have seen an example of how to read numbers from a file and find their average itโs time to practice some more. Pick one of the following options:
Hint: To do so, ย youโll first have to find the average (as we did before). Then, you have to โresetโ the file by closing it and re-opening it, then you can read the file again and compute the standard deviation using the following:
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void) {
FILE *ifile; /* ifile is a variable name - you could use any other name here.
However, the '*' is important. We'll learn about it more later.
We call this a file pointer. */
int i, num, N, sum;
N = 10; /* we are told there are 10 numbers in the file */
ifile = fopen("my_first_file.txt", "r"); /* open file for reading.
The "r" stands for reading. */
sum = 0;
for (i = 0; i<N; i++) {
fscanf(ifile, "%d", &num);
printf("I read %d from the file. \n", num);
sum += num;
}
fclose(ifile);
printf("The sum of the numbers read is %d. The average is %.2f.", sum, (float) sum / N);
return(0);
}
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void) {
FILE *ifile; /* ifile is a variable name - you could use any other name here.
However, the '*' is important. We'll learn about it more later.
We call this a file pointer. */
int i, num, N, sum;
N = 10; /* we are told there are 10 numbers in the file */
ifile = fopen("my_first_file.txt", "r"); /* open file for reading.
The "r" stands for reading. */
sum = 0;
for (i = 0; i<N; i++) {
fscanf(ifile, "%d", &num);
printf("I read %d from the file. \n", num);
sum += num;
}
fclose(ifile); /* closes the file */
printf("The sum of the numbers read is %d. The average is %.2f.", sum, (float) sum / N);
return(0);
}
Modify the program we just wrote so that instead of reading numbers, it reads characters from the file my_second_file.txt. Print out the characters you read from the file one next to the other.
As before, for now we are telling you how many characters are in the file, namely 9. So that you know what to expect, here is what the contents of the file looks like:
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void) {
FILE *ifile; /* ifile is a variable name - you could use any other name here.
However, the '*' is important. We'll learn about it more later.
We call this a file pointer. */
int i, num, N, sum;
N = 10; /* we are told there are 10 numbers in the file */
ifile = fopen("my_first_file.txt", "r"); /* open file for reading.
The "r" stands for reading. */
sum = 0;
for (i = 0; i<N; i++) {
fscanf(ifile, "%d", &num);
printf("I read %d from the file. \n", num);
sum += num;
}
fclose(ifile); /* closes the file */
printf("The sum of the numbers read is %d. The average is %.2f.", sum, (float) sum / N);
return(0);
}