Read in numbers from file

This is a discussion on Read in numbers from file within the C Programming forums, part of the General Programming Boards category; Hey, I'm new to this so hi I've a .txt file with 96 numbers in it eg. 2719 1058 4021 ...

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    1

    Exclamation Read in numbers from file

    Hey, I'm new to this so hi

    I've a .txt file with 96 numbers in it
    eg.
    2719
    1058
    4021
    ...

    I need a while loop to read how many numbers there are in the .txt file because the file changes and the number of numbers changes.

    EOF was used but I'm not really clear on that.

    Heres my sexeh code
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main(void)
    {
        FILE *fp;
        int i, c;
        fp = fopen("elec_load_data.txt", "r");
        i=0;
        while ((c = fgetc(fp)) != EOF)
        {
            putchar (c);
            i++;
            printf("%d\n", i);    // to see if the counter is counting
        }
        fclose(fp);
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    I would recommend using fgets(buffer, BUF_SIZE, fp) to read one line at a time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read numbers from a text file
    By fred_maes in forum C Programming
    Replies: 5
    Last Post: 08-13-2011, 06:43 PM
  2. Read numbers from file to std::vector
    By Petike in forum C++ Programming
    Replies: 2
    Last Post: 12-24-2010, 03:33 AM
  3. Read formatted numbers from a txt file
    By xldie in forum C Programming
    Replies: 1
    Last Post: 12-19-2006, 09:43 PM
  4. read numbers from a file
    By haroonie in forum C Programming
    Replies: 5
    Last Post: 03-27-2005, 10:30 PM
  5. Read words and numbers from a file
    By atari400 in forum C Programming
    Replies: 5
    Last Post: 11-04-2004, 03:55 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21