gpt4 book ai didi

c++ - WriteFile 函数返回成功但无法查看文件系统中的文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:53:34 26 4
gpt4 key购买 nike

我正在尝试将 unsigned short 和 unsigned char 数组内容写入 .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));
}

关于c++ - WriteFile 函数返回成功但无法查看文件系统中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23881359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com