Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

read numbers from file

read numbers from file

read numbers from file

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?

RE: read numbers from file

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.

RE: read numbers from file

Of course, you may get data stream on number by number basis. That's a code sceleton:


/* 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 */

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close