Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Reading in lines from a file

  1. Oct 23, 2007 #1
    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. jcsd
  3. Oct 23, 2007 #2

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    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
  4. Oct 23, 2007 #3
    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.
     
  5. Oct 23, 2007 #4

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Reading in lines from a file
  1. Reading from file (Replies: 3)

Loading...