View previous topic :: View next topic |
Author |
Message |
jb
Joined: 01 Mar 2007 Posts: 1
|
Posted: Thu Mar 01, 2007 4:57 pm Post subject: Read file as binary |
|
|
I need to read in a file, but not as text. I need to process it as binary.
bit[] bFileContent = cast(bit[])read(sFileName); doesn't seem to work as I anticipated, it just reads in characters and declares them all true.
How could I either read in a file as a binary array or break up what I read into a binary array?
Thanks. |
|
Back to top |
|
|
pqnelson
Joined: 03 Jun 2007 Posts: 13 Location: Davis
|
Posted: Wed Oct 31, 2007 5:24 pm Post subject: |
|
|
Try using the std.c.stdio module's fread() method, I think it can be used to read in binary stuff. Ultimately this is what I would do:
Code: | import std.c.stdio;
int main(char[][] args)
{
char[] path = "/home/pqnelson/myBinaryFile"; // the path using Unix path style
byte[] data; //array where we will store the data read in from the file
FILE *file; // the file descriptor pointer
file = open(path, "rb"); // opens the file with flags indicating you want to read and it is binary
uint nBytesRead = 25; //number bytes to read in
if(fread(cast(void*)data, 1, nBytesRead, file) <= 0)
{
throw new Exception("The computer hates me! It won't read in the file or more than likely perhaps the file doesn't exist?");
}
// do what you want with the binary stuff...
}
|
Unfortunately you will have to be using bitwise operators to manipulate the bits themselves, but that's life.
It's more efficient than using a bitarray, I think, because if you have n bits you would be using an n byte sized array. That's just inefficient. |
|
Back to top |
|
|
Linker
Joined: 06 Nov 2006 Posts: 29 Location: Almaty, Kazakhstan
|
Posted: Wed Nov 14, 2007 11:39 am Post subject: |
|
|
What do you mean binary? I suppose you don't want line-endings interpreted?
Then you should do something along the lines of:
Code: |
// ...some code...
auto contents = cast( ubyte[] )std.file.read( filename );
// ...more code...
|
Bit is just a typedef for bool, so casting to bit[] doesn't make much sense here. |
|
Back to top |
|
|
|