Jump to content

Recommended Posts

Posted

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

  • Replies 0
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...