|
-
May 29th, 2003, 11:26 PM
#1
Member
reading a file as binary
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 its not broken it can still be inproved.
-
May 29th, 2003, 11:46 PM
#2
-
May 30th, 2003, 02:31 AM
#3
If you use visual basic you can use
Open "filename" for binary as #n
Then you can use Get to read the binary
-
May 30th, 2003, 01:35 PM
#4
with c++ it's something like this:
// open a file in "read binary" mode
filePtr = fopen(filename, "rb");
-
May 31st, 2003, 02:58 AM
#5
Senior Member
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;
}
\"Trying to outsmart a compiler defeats much of the purpose of using one.\" — Kernighan & Plauger, The Elements of Programming Style.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|