In WINDOWS I'm trying to MANUALLY copy a file from one location to another. However, it won't copy binary files correcty. A file will get created and it will be the same size as the copied file but the data won't be right. What am I doing wrong:
copy_file("C:\\temp\\file.mp3", "C:\\temp\\file2.mp3" //file.mp3 is a valid mp3 file and file2.mp3 is the file being created
BOOL CMyProgramDlg::copy_file(CString strFilePath, CString strNewFilePath)
{
int fd = 0;
int wfd = 0;
unsigned int bytesread, totalbytes = 0;
CString str;
char buffer[MTU+1];
if((fd = _open(strFilePath.GetBuffer(strFilePath.GetLength()), _O_RDONLY | _O_BINARY)) == -1) {
MessageBox("Failed to open the file <" + strFilePath + ">.", "Error:copy_file()", MB_ICONERROR | MB_OK);
return FALSE;
}
if((wfd = _open(strNewFilePath.GetBuffer(strNewFilePath.GetLength()), _O_RDWR | _O_CREAT | _O_TRUNC | _O_BINARY, _S_IREAD | _S_IWRITE)) == -1) {
MessageBox("1 Failed to create the file <" + strNewFilePath + ">.", "Error:copy_file()", MB_ICONERROR | MB_OK);
return FALSE;
}
while((bytesread = _read(fd, buffer, MTU)) > 0) {
buffer[bytesread] = '\0';
totalbytes += bytesread;
if(_write(wfd, buffer, sizeof(buffer)) == -1) {
MessageBox("write error", "Error", MB_OK | MB_ICONERROR);
return FALSE;
}
}
_close(fd);
_close(wfd);
MessageBox("Done!"
return TRUE;
}
It copies the file just fine but the data isn't right. It does work for ASCII text files.
Thanks.
-bitwise
copy_file("C:\\temp\\file.mp3", "C:\\temp\\file2.mp3" //file.mp3 is a valid mp3 file and file2.mp3 is the file being created
BOOL CMyProgramDlg::copy_file(CString strFilePath, CString strNewFilePath)
{
int fd = 0;
int wfd = 0;
unsigned int bytesread, totalbytes = 0;
CString str;
char buffer[MTU+1];
if((fd = _open(strFilePath.GetBuffer(strFilePath.GetLength()), _O_RDONLY | _O_BINARY)) == -1) {
MessageBox("Failed to open the file <" + strFilePath + ">.", "Error:copy_file()", MB_ICONERROR | MB_OK);
return FALSE;
}
if((wfd = _open(strNewFilePath.GetBuffer(strNewFilePath.GetLength()), _O_RDWR | _O_CREAT | _O_TRUNC | _O_BINARY, _S_IREAD | _S_IWRITE)) == -1) {
MessageBox("1 Failed to create the file <" + strNewFilePath + ">.", "Error:copy_file()", MB_ICONERROR | MB_OK);
return FALSE;
}
while((bytesread = _read(fd, buffer, MTU)) > 0) {
buffer[bytesread] = '\0';
totalbytes += bytesread;
if(_write(wfd, buffer, sizeof(buffer)) == -1) {
MessageBox("write error", "Error", MB_OK | MB_ICONERROR);
return FALSE;
}
}
_close(fd);
_close(wfd);
MessageBox("Done!"
return TRUE;
}
It copies the file just fine but the data isn't right. It does work for ASCII text files.
Thanks.
-bitwise