我试图将无符号短和无符号字符数组内容的内容写入.img文件。我使用WriteFile方法来做同样的事情。似乎WriteFile函数成功地将数组内容写入文件,但主要问题是我无法在文件系统中查看该文件。以下是我用来将数据写入文件的两种方法。
void createImageFile(unsigned short* src,int srcLength,const char* fileName)
{
DWORD dwBytesWritten = 0;
unsigned short *dest = new unsigned short[srcLength];
if(is_file_exist(fileName))
{
remove(fileName);
}
HANDLE hFile = CreateFile(LPCWSTR(fileName), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD e = GetLastError();
if(hFile)
{
memcpy(dest,src,srcLength*sizeof(unsigned short));
bool b = WriteFile(hFile,dest,srcLength,&dwBytesWritten,NULL);
if(!b)
{
DWORD e = GetLastError();
} CloseHandle(hFile);
}
if(dest)
{
delete[] dest;
dest = NULL;
}
}
void createImageFile(unsigned char* src,int srcLength,const char* fileName)
{
DWORD dwBytesWritten = 0;
unsigned short *dest = new unsigned short[srcLength];
if(is_file_exist(fileName))
{
remove(fileName);
}
HANDLE hFile = CreateFile(LPCWSTR(fileName), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD e = GetLastError();
if(hFile)
{
memcpy(dest,src,srcLength*sizeof(unsigned short));
bool b = WriteFile(hFile,dest,srcLength,&dwBytesWritten,NULL);
if(!b)
{
DWORD e = GetLastError();
} CloseHandle(hFile);
}
if(dest)
{
delete[] dest;
dest = NULL;
}
}
我不确定我到底做错了什么。我无法查看指定路径上的那些文件。有人能帮帮我吗?我想强调的另一件事是,上面的代码是非托管代码的一部分,应该驻留在dll中。
不能将fileName
强制转换为宽字符串。
别忘了关闭文件。
CreateFile
失败时返回INVALID_HANDLE_VALUE
不为零。因此,您的错误检查条件不正确。
复制src
到dest
是完全没有必要的。也不需要在删除后将指针设置为NULL
。
同样,在remove(fileName)
和CreateFile
之间有一个竞争条件。您不需要删除-设置dwCreationDisposition
就足够了。
整个函数可以写成:
void createImageFile(unsigned short* src, int srcLength, const char* fileName)
{
using namespace std;
ofstream stream(fileName, ios_base::binary | ios_base::trunc);
stream.write(src, srcLength * sizeof(unsigned short));
}