|
-
February 10th, 2003, 01:38 AM
#1
File reading/writing problems...
I'm having some problems with file writing under C++. I've tried using OFSTREAM, FOPEN, and _OPEN along with their respective write functions however they arent doing what I expect of them.
I'm trying to open a file for binary writing. If the file exists or not, who cares, just write over it with this new file. And if while writing an error occurs such as "disk space is full" or "media error" then mention it so that I can abort my current operation. OFSTREAM's write() doesnt seem able to do this with its BAD(), FAIL(), or GOOD() functions, nor does it have a bytes written value. FOPEN's fwrite() seems to always return back the "count" value regardless of how much it actually wrote. And _OPEN just seems picky about a file existing and writing over top of it.
Can someone provide me with properly working code for writing out a binary file to disk. If the filename already exists simply write over top. If disk space is full or a media error occurs return back an error so that i can take the appropriate action. For instance if I try to write the file to 3.5" diskette with 0 bytes free space return an error that the data was written in full.
I'm using MS Visual C++ 6, MS Windows 2000.
Thanks.
-
February 10th, 2003, 06:04 AM
#2
See the example below. I hope it helps.
Code:
#include <windows.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string get_last_error()
{
string result;
LPTSTR lp_buffer = 0;
BOOL b = FormatMessage
(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
::GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT),
(LPTSTR) &lp_buffer,
0,
0
);
if ( b )
{
result = lp_buffer;
LocalFree( lp_buffer );
}
return result;
}
int main()
{
ofstream os( "A:\\TEST.BIN", ios:: out | ios:: trunc | ios:: binary );
if ( ! os )
{
cerr << get_last_error();
return 1;
}
char p_data[0xffff];
size_t size = sizeof(p_data) / sizeof(p_data[0]);
size_t to_write = 9999;
while ( to_write-- && os.write( p_data, size ) )
/*nop*/;
if ( ! os )
{
cerr << get_last_error();
return 2;
}
return 0;
}
Regards,
ZDF
What is good is twice as good if it's simple.
"Make it simple" is a complex task.
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
|
Click Here to Expand Forum to Full Width
|