Hi all,

I'm having a prob with loading a file into an array.

I'm fine with opening the file but when it come to the fread command i seem to be failing as the document size will be variable, so how can i state a file size as "num_of_elements".

if this is not clear, then my basic idea is:

i want to open a file in 128 bit chunks and load it into an array so i can perform function on the array. Thats about it.

I would provide code, but i've butchered it that much it aint much use.

any help would be greatly appreciated.

cheers.

>so how can i state a file size as "num_of_elements"
There are basically two ways: 1) read the file and dynamically resize an array accordingly:

#include <stdio.h>
#include <stdlib.h>

int main ( void )
{
  FILE *in = fopen ( "test.txt", "r" );

  if ( in != NULL ) {
    char *myarray = NULL;
    char buffer[5];
    size_t i, n, curr = 0, size = 0;

    while ( ( n = fread ( buffer, 1, 5, in ) ) > 0 ) {
      char *save;

      size += n;
      save = realloc ( myarray, size );

      if ( save == NULL )
        break;

      myarray = save;

      for ( i = 0; i < n; i++ )
        myarray[curr++] = buffer[i];
    }

    for ( i = 0; i < size; i++ )
      printf ( "%c", myarray[i] );

    free ( myarray );
  }

  return 0;
}

and 2) gather the number of items in the array and do a one time allocation:

#include <stdio.h>
#include <stdlib.h>

int main ( void )
{
  FILE *in = fopen ( "test.txt", "r" );

  if ( in != NULL ) {
    char *myarray = NULL;
    size_t i, size = 0;
    int ch;

    while ( ( ch = fgetc ( in ) ) != EOF )
      ++size;

    rewind ( in );
    myarray = malloc ( size );

    if ( fread ( myarray, 1, size, in ) == size ) {
      for ( i = 0; i < size; i++ )
        printf ( "%c", myarray[i] );
    }

    free ( myarray );
  }

  return 0;
}

Any solution will be a variation of that, such as processing the file in smaller chunks individually rather than growing an array, or getting the size of the file with some non-portable method such as fstat.

cheers for the prompt reply,

will this still work when dealing with binary files, as i've noted within your code you only use the 'r' identifier

many thanks

>will this still work when dealing with binary files
It should, though a little more detail in what kind of data you're working with and what you're doing would help me to give you a more definite answer.

sorry about that.. basically i will be attempting to load a number of different files and there is no pre-defined structure to them.. the over-all code will go to form part of a basic form of encryption, where by the file will e loaded in binary. Block of the data will then be transformed and output into a file.

Hope this is of more help

This article has been dead for over six months. Start a new discussion instead.