# Reading in lines from a file

1. Oct 23, 2007

### edosqclbe699

I have the Dev C++(I am writing in C language) compiler and I need help on how to read in specific lines in a file and complete calculations on them. I need to read in a .txt file (I know how to do this, however I dont know how to read in the specific lines in a file) that has a column of about 20 numbers. For my assignment I need to determine the number of lines in the file, the average value of the numbers, the max and min of the numbers, and the standard deviation of the numbers. So far in class we have covered functions, pointers, and loops. I am assuming I need to use a function but I have no idea how. Can someone generally tell me the way to read in the lines into the program so I can compute these 4 things.

2. Oct 23, 2007

### mgb_phys

This should get you started:

int main() {
FILE *file;
char line[80];
file = fopen("numbers.txt", "r");

if(file) {
while(fgets(line, 80, file)) {
// "line" contains characters from current line here
}

fclose(file);
}
return 0;

}

Last edited: Oct 23, 2007
3. Oct 23, 2007

### edosqclbe699

I actually need to create a function in a separate file that will return the values of the number of lines in the file, the average of the values, the max and min of the values, and the standard deviation of the values. Sorry for not being more specific before but, can anyone give me a little advice on how to do it this way.

4. Oct 23, 2007

### mgb_phys

It's a homework question? The above should get you started.
To convert the line to a number look at atof() or fscanf()
There is a formula to calculate the standard deviation from running totals without having to re-read the numbers subtracting the mean. Look on wiki for details.
If these are large numbers be careful about overflow, you should probably use doubles for the sums.