Question:
C programming basics. Can anyone help me with File Input? Simple question for the pros (please help!)?
Matt H
2010-02-27 11:52:45 UTC
Hello,
So im working with a ".txt" file input in C programming. I am a beginner. My txt file has a bunch of integers which looks some thing like:

3
5 4 6 5 3 4 5 6
3 5 6 7 8 9 4 3
2 5 6 7 8 8 8 3

Does anybody know the program code how to add up each line of numbers separately? (not including the single 3 on line 1).

NOTE: once I have the code for how to add up the values from each line, I will be able to 'printf' it into my program and go on from there.


Thank You.
Matt H.
Three answers:
Nick T
2010-02-28 05:20:59 UTC
At least attempt your own homework!





Assuming that the 3 is the number of lines to read, and each line contains 8 integers



PSEUDO CODE



declare fp as FILE

declare number as integer value 0

declare total as integer value 0



OPEN fp for INPUT from "sample.txt"

IF (fp is a valid file) THEN

..input linecount from fp

..LOOP FOR linecount

....total = 0

....LOOP FOR 8 items

......input number from fp

......total = total + number

....END LOOP

....output Total for line (loop index) is (total)

..END LOOP

..close fp

END IF
2016-05-31 06:10:46 UTC
A faster, better way would be to get the size of the file. I rarely use C++, but under C: f=fopen("filename.txt", "rb"); fseek(f, 0, SEEK_END); size=ftell(f); fseek(f, 0, SEEK_SET); Then allocate a "size+1" byte string, read the file contents into that array, set the last index to '0' and display the string. It's faster than character-by-character and you don't have to worry about the nuisances of EOF. (Also free the string you've allocated when you don't need the string any more.)
ScottyO
2010-02-27 19:31:34 UTC
What OS? A Unix OS and a windows OS would have different answers.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...