Reputation: 87
I'm having trouble with win32. I have to write some dynamic data to a file in win32 using c++. I know the basics of how to write strings to the file, but how can we write a data of ints, floats etc to a file.
I have a file which I'm copying the data to another newly created file. I need to write the data of ints, floats etc to this file at top. I know we can add the data by
char buff[] = "hello";
and copy this to file, I don't know how I can do this with different kinds of data types. Any help?
char buf[] = "hello"; //Null terminate
LPVOID lpMsgBuf;
DWORD byteWritten = 0;
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
BOOL ReadFileReturn;
HANDLE hFile = CreateFile("MYFILE.blo", // open MYFILE.blo
GENERIC_WRITE | GENERIC_READ,
FILE_SHARE_READ, // share for reading
NULL, // no security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr
ReadFileReturn = ReadFile(hFile,buf,30,&byteWritten,NULL);
if(ReadFileReturn)
{
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL);
WriteFile(hStdOut,buf,sizeof buf,NULL,NULL);
}
else
{
WriteFile(hStdOut,"It Failed",sizeof "It Failed",NULL,NULL);
}
Upvotes: 0
Views: 1117
Reputation: 1409
That depends how you are opening your file (in which mode actually). If you have opened them in a text mode, everything regardless of its type will get written in the form of string/text. Otherwise you can choose to open file in binary mode. In that mode int
will be written as int
, float
will be written as float
etc.
Here's a link for describing the difference between both types of files http://www.fileinfo.com/help/binary_vs_text_files
You can perhaps try something like:
char str[80] = "";
int a = 1, b = 2;
int n = sprintf(str, "%d", a+b);
DWORD bytesWritten;
WriteFile(fileHandle, str, strlen(str), &bytesWritten, NULL);
Upvotes: 1
Reputation: 12700
Check this:
http://www.cplusplus.com/reference/ostream/ostream/write/
So basically you do this:
....
std::ofstream myfile("filename");
double my_data = 15;
myfile.write( static_cast< const char*>(&my_data), sizeof( double ) );
...
The previous snippet is a bit crude, you might need to check issues like endiannes and alignment.
Upvotes: 0