I am writing a program which has to create a file, map it to the memory and then write two-dimensional array of doubles to it. I encounter a problem when I look into the file. It is full of not expected values. I guess, this problem is related to casting, but can't come up with solution. So, the question is, how to convert array of doubles to char *? Hope someone can give me a clue to solve this problem.
int main(int argc, char **argv)
{
HANDLE plik, mappedFile;
char *poi;
LPCWSTR fileName = L"plik.txt";
double tab[8][12];
createMatrix(tab); // here I fill the array with values
// creating file
// mapping the file
poi = (char *)MapViewOfFile(
mappedFile,
FILE_MAP_ALL_ACCESS,
0,
0,
0);
if (!poi)
{
puts("Can't allocate Memory!");
abort();
}
memcpy(poi,tab,96*sizeof(double));
UnmapViewOfFile((void*)poi);
CloseHandle(mappedFile);
CloseHandle(plik);
getchar();
return 0;
}
I think your code is working, the file contains the double numbers, but remember that it's a binary format with floating point format, so a text editor will just show it as some junk. Try a hex editor, and check the double format. Or try to read it back.
The major problem with your approach is that it's not cross platform, a machine with different endianness wouldn't be able to properly read it (this may or may not be a problem for you).
What you want is serialization . The simplest version would just print the numbers in the file (with some user-defined limited precision) - eg with sprintf
..
Are you looking for something like this:
char* poi = new char[8*12*sizeof(double)];
int index = 0;
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 12; j++)
{
*(double*)(poi + index) = tab[i][j];
index+=sizeof(double);
}
}
I suggest you to replace file mapping with simple WriteFile function. It can be faster for many applications.
WriteFile(plic, tab, sizeof(tab), 0, 0);
will serialize your data accurately and quickly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.