The code below creates a file, it stores in it all the numbers from 1 to 100. Closes the file. Then, it opens the file, reads all the numbers one after the other and attempts to find the sum of them. The sum should be 1+2+3+.....+98+99+100 = 5050. Unfortunately, i cannot understand why it counts TWICE the last number. This is what it does:
1+2+3+.....+98+99+100+100 = 5150. I imported and used functions only from the c language library.
while(!eof) is wrong because it tests for something that is irrelevant and fails to test for something that you need to know. The result is that you are erroneously executing code that assumes that it is accessing data that was read successfully, when in fact this never happened.
thank you. The first 23 lines are fine.They will store numbers 1- 100 in a file. I tetsed it.
The problem is with the lines from line 28 and below. I understand that i need to check the return code BEFORE i make an addition. I am stuck because i cannot come up with that very simple code line to check the return code so as to prevent the extra unwanted calculation.
I know that i open the file in text mode and i am using a function feof() which is more ideal for binary mode, but it seems to be working,i cannot use EOF in the while statement. Maybe i run out of ideas how to write some proper code lines :(
The first 23 lines are fine.They will store numbers 1- 100 in a file. I tetsed it.
That doesn't mean it is right :+) Just use fprintf, no EOF. It returns a value as well, so you can check that after every write operation, and handle any rare errors.
The answers to your other questions are in the link I posted.
Use the return value from fscanf to see if it worked or not. If it does, then proceed. Otherwise, check for EOF and break or print an error message (or otherwise handle) if no EOF.
The big thing to remember here: EOF is set after a failed read operation.