Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Writing binary data files 1

Status
Not open for further replies.

bitwise

Programmer
Mar 15, 2001
269
US
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(&quot;Failed to open the file <&quot; + strFilePath + &quot;>.&quot;, &quot;Error:copy_file()&quot;, 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(&quot;1 Failed to create the file <&quot; + strNewFilePath + &quot;>.&quot;, &quot;Error:copy_file()&quot;, 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(&quot;write error&quot;, &quot;Error&quot;, MB_OK | MB_ICONERROR);
return FALSE;
}
}
_close(fd);
_close(wfd);
MessageBox(&quot;Done!&quot;);
return TRUE;
}

It copies the file just fine but the data isn't right. It does work for ASCII text files.

Thanks.
-bitwise
 
Four words, &quot;Son of a bitch&quot;.

Thanks, :)
-bitwise
 
Those who might have cared. I also changed:

&quot;sizeof(buffer)&quot; to &quot;bytesread&quot;

in the _write function.

-bitwise
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top