Thread: loading binary file into an int array!!

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    4

    loading binary file into an int array!!

    hi,
    I have an array of ints saved as a binary file and now im trying to load that file back into the array ... this is what i have so far, not sure what to do from here.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX_SIZE 100
    
    int main(int argc, char*argv[])
    {
       FILE *intArrayFile;
       char *buffer;
       long size;
       int new_array[MAX_SIZE];
    
       intArrayFile = fopen("intFile", "rb");
       size = ftell(intArrayFile);
       rewind(intArrayFile);
       buffer = (char*)malloc(size);
       fread(buffer, 1, size, intArrayFile);
    
       /*ive loaded the file into the buffer, now how do i make
          set the new_array to the buffer?*/
    
       return 1;
    }
    many thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > buffer = (char*)malloc(size);
    Don't use a cast

    In fact, you don't even need the malloc
    Code:
    size_t num;
    num = fread( new_array, sizeof(int), MAX_SIZE, intArrayFile);
    num will contain how many int's you read in.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    4
    Thanks for that.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Replies: 4
    Last Post: 11-23-2003, 07:15 AM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM