3

I have a file that in C++ I load into array using below code:


int SomeTable[10000];

int LoadTable()
{
    memset(SomeTable, 0, sizeof(SomeTable));
    FILE * fin = fopen("SomeFile.dar", "rb");
    size_t bytesread = fread(SomeTable, sizeof(SomeTable), 1, fin);
    fclose(fin);
}

The file is binary code of 10000 integers, so in C++ it could be directly loaded into memory. Is there a fansy way of doing that in Python?

best regards, Rok

2

1 Answer 1

2

Let's write an array into a file using a short C code:

int main ()
{
  FILE * pFile;
  int a[3] = {1,2,3};
  pFile = fopen ( "file.bin" , "wb" );
  fwrite (a , 1 , sizeof(a) , pFile );
  fclose (pFile);
  return 0;
}

The binary file can be loaded directly into a python array

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import array
>>> a=array.array('l') # 'l' is the type code for signed integer
>>> file=open('file.bin','rb')
>>> a.read(file,3)
>>> print a
array('l', [1, 2, 3])
>>> print a[0]
1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.