C file function questions

Joined
Jan 10, 2007
Messages
43,898
Location
In The Machine
I am taking a C++ class this semester. It is right now covering C material*and will switch to C++ material mid-semester. Anyway, in the textbook, there is the following code:

#include

int main(void)
{

int a, sum = 0;
FILE *ifp, *ofp;

ifp = fopen("my_file", "r");
ofp = fopen("outfile", "w");
...

The textbook then explains*the above code, saying that*it opens*two files in the current*directory. Is the current directory by default*the directory of the executable or the root directory?

It then proceeds to say that if my_file contains integers, we want to sum them and put the result in outfile, we can write:

while(fscanf(ifp, "%d", &a) == 1)
*** sum += a;
fprintf(ofp, "The sum is %d.\n", sum);

Since this is in the textbook, I would expect it to sum all of the values and print the growing sum as the summation occurs, but it looks like an infinite loop to me.*I can see how it could end, being that the pointer reaches the end of file, but I do not see how it increments itself. Does this code even work and if it does, how does it work?

After this it calls fclose().


More...

View All Our Microsoft Related Feeds
 
Back
Top