Thread: Read in numbers from file

  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,834
    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, 04:33 AM
  3. Read formatted numbers from a txt file
    By xldie in forum C Programming
    Replies: 1
    Last Post: 12-19-2006, 10:43 PM
  4. read numbers from a file
    By haroonie in forum C Programming
    Replies: 5
    Last Post: 03-27-2005, 11:30 PM
  5. Read words and numbers from a file
    By atari400 in forum C Programming
    Replies: 5
    Last Post: 11-04-2004, 04:55 PM