Has anyone got any information on how to read a file as binary. This is for a few programs im making one is to split a file into several parts and the other is to send files over winsock, any information would be great
thanx trials
Printable View
Has anyone got any information on how to read a file as binary. This is for a few programs im making one is to split a file into several parts and the other is to send files over winsock, any information would be great
thanx trials
If you use visual basic you can use
Open "filename" for binary as #n
Then you can use Get to read the binary
with c++ it's something like this:
// open a file in "read binary" mode
filePtr = fopen(filename, "rb");
Actually, that is more C file I/O then C++. C++ does support C I/O, so you may see that in a C++ program, but more then likely you will not.
C++ would use the ifstream (for reading in a file) and ofstream (for writing out a file) classes for file I/O.
ifstream in(“filename”, ios::binary|ios::nocreate);
ofstream out(“filename”, ios::binary);
Here is an example of some code that uses binary I/O to copy a file entered on the command line. More error handling could be added but you get the idea.
Code://-----------------HEADERS---------------
#include<iostream.h>
#include<fstream.h>
//----------------PROTOTYPES---------------
int binaryCopy(char *source, char *destination);
void usage();
//---------------DRIVER---------------------
int main(int argc, char *argv[])
{
cout<<"Starting bincp...."<<endl;
if(argc != 3)
{usage();return 1;}
if(!binaryCopy(argv[1],argv[2]))
cout<<"Error in file argument."<<endl;
else
cout<<"bincp sucessful."<<endl;
return 0;
}
//----------------FUNCTIONS---------------------
int binaryCopy(char *source, char *destination)
{
//create I/O streams
ifstream in(source, ios::binary|ios::nocreate);
ofstream out(destination, ios::binary);
//if file fails, die and return 0/false
if(!in||!out) return 0;
char byte = 0;
//do until EOF
while(in)
{
in.read(&byte,1);
out.write(&byte,1);
}
return 1;
}
void usage()
{
cout<<"bincp <sourceFile> <destinationFile>"<<endl;
}