none
none

Reputation: 373

Reading information from text files, line by line

I want to learn how to read .txt files in C, line by line so that the information in each line can be used in loops etc. I don't have a homework exercise for this but I need to figure it out for a project to write a script for an astronomy package.

So in order to learn how to do this I created a file called list.txt with the numbers 1,2,3,4,5,6,7,8,9 each on separate lines and I want the program to sum the values on each line. I also created an output file called sum.txt and the program is supposed to sum the lines, and print the sum to the output file.

I am getting an error when I run the program and I'm not sure what the problem is as I don't fully understand this. I got this program in a book on C and tried to modify it to run it on my PC.

The reason I need to be able to do this is because I need to take information from each line in a list (each line containing one string). But I want to learn to do it with numbers first.

Here's the code:

#include<stdio.h>

int main(void)
{
    int a, sum = 0;
    FILE *ifp, *ofp;
    ifp = fopen("list.txt", "r");
    ofp = ("sum.txt", "w");
    while (fscanf(ifp, "%d", &a) == 1)
    {
        sum += a;
        fprintf(ofp, "The sum is %d. \n", sum);
        fclose(ifp);
    }
    return 0;
}

Upvotes: 3

Views: 716

Answers (2)

codaddict
codaddict

Reputation: 455460

You need to close the input file after the loop and move the fprintf outside the loop too:

} // end of while loop
fprintf(ofp, "The sum is %d. \n", sum);
fclose(ifp);

Also don't forget to do error checking and ensure that you've opened the files before you go on and to IO on them.

Upvotes: 0

interjay
interjay

Reputation: 110202

You forgot to write fopen here:

ofp = ("sum.txt", "w");

Also, you should move the fclose (and possibly the fprintf) out of the while loop, since you only want to close the file after reading all the lines.

Upvotes: 6

Related Questions