Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read numbers from file

Status
Not open for further replies.

fluffypancakes

Technical User
Mar 6, 2009
1
CA
i have a file where numbers are stored in a row separated by a space: 23 34 24 1 5 90, ... all positive integers. how in c do i make a loop that first works with 23, then with 34, then with 24, etc... do i have to go byte by byte or is there a way to just go number by number?
 
Use fgets() to read a line of numbers into a buffer; use a loop to read the whole file.

Use strtol() to convert each "23" into 23 (say); use a loop to convert the whole buffer.
strtol() can update a pointer to where it got to, making it easy to walk a string.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Of course, you may get data stream on number by number basis. That's a code sceleton:
Code:
/* Let N is a number of array elements */
FILE* f = fopen(filename,"r");
if (!f) {
    /* can't open, stop processing */
}
for (i = 0; i < N && fscanf(f,"%d",&a[i]) == 1; ++i)
    ;
if (!feof(f)) { /* not all data processed */
    if (i < N) {
        /* error occured (i/o err or bad data) */
    } else {
        /* No more memory */
    }    
}
fclose(f);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top