Thread: Reading integer from file.

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    30

    Reading integer from file.

    Hi. I am very happy to join this forum and hope that someone can help me with this little problem of mine:

    I need to read a list of space-separated integers from a txt-file into my program(i.e. into an array defined by myself) for processing. Using fread() from the stdio library, I have tried doing this, but fread() seems to be able to handle char's only.

    Is there something I have missed about an application of fread() for integers, or is there some other standard function or method that can help me?

    Thanks in advance.

    esbn.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Try using fscanf(file, "%d", &value) with a text file.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,212
    Code:
    #include <stdio.h>
    
    int main(void) 
    {
        FILE *fp = fopen("input.txt", "r");
        int array[5] = { 0 };
        int i;
       
        for (i = 0; i < 5; i++) {
            fscanf(fp, "%d", &array[i]);
        }
    
        fclose(fp);
        return 0;
    }

  4. #4
    Registered User
    Join Date
    Mar 2006
    Posts
    30
    Thanks a lot for the answer guys, really appriciate the fast reply. Im in Shanghai, and here its past my bedtime, so I'll work with it tomorrow.

    Cheers.

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Remember to also check the return value of fscanf to see whether or not an integer was assigned -- if not, it might be another reason to break the loop.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Reading Input from file (Integer array)
    By Govalant in forum C Programming
    Replies: 9
    Last Post: 07-23-2007, 06:13 PM
  4. load gif into program
    By willc0de4food in forum Windows Programming
    Replies: 14
    Last Post: 01-11-2006, 10:43 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM