How Can I Read Specific Lines from a File in C Language Using Dev C++ Compiler?

  • Context: C/C++ 
  • Thread starter Thread starter edosqclbe699
  • Start date Start date
  • Tags Tags
    File Lines Reading
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 5K views
edosqclbe699
Messages
4
Reaction score
0
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 don't 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.
 
on Phys.org
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:
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.
 
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.