Thread: Reading a list of ints from file into an array

  1. #1
    Registered User
    Join Date
    Mar 2007
    Posts
    43

    Reading a list of ints from file into an array

    I'm having a little difficulty understanding how to read a file into an array - in this case a file of numbers (ints) into an array. I know how to open a file for reading, but once I have it open how can I read it's contents into an array? For example let's say I have the following code:
    Code:
    FILE* sp;
        int num;
        sp = fopen("rut.txt","r");
       while (fscanf(sp,"%d",&num)==1)
           printf("%d\n",num);
    Now, lets say that the file "rut.txt" is a file full of numbers like this
    124
    5
    -5
    0
    9
    etc...

    How can I fill an array directly from the stream? I guess I'm not understanding thee C api very well

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Well, first you need the array to store the numbers into. If you know your file will only contain a certain amount of numbers then you can allocate a fixed size array to deal with them... if not, then you'd likely need to dynamically allocate/reallocate with malloc/realloc to accommodate an unknown number of values.

    Then, you'll need a counter that starts at zero and is incremented by one each time through the read loop. This is used as an index into your array where you assign the value you've just read from the file into that specific index of the array.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting linked list please help with CODE
    By scarlet00014 in forum C Programming
    Replies: 3
    Last Post: 09-27-2008, 11:24 PM
  2. Reading int's from file to array HELP plz
    By GARiMTO in forum C Programming
    Replies: 3
    Last Post: 12-14-2007, 06:12 AM
  3. Reading integers from a File into an Array
    By bobby19 in forum C Programming
    Replies: 13
    Last Post: 10-09-2006, 01:36 AM
  4. Reading Characters from file into multi-dimensional array
    By damonbrinkley in forum C Programming
    Replies: 9
    Last Post: 02-24-2005, 01:31 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM