WriteFile函数返回成功,但无法查看文件系统中的文件
WriteFile function retuns success but not able to view file in file system
我试图将无符号短和无符号字符数组内容的内容写入.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++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 如何传递多个 std::文件系统选项?
- 遍历顺序由 std::文件系统directory_iterator给出
- libstdc++ 文件系统中未初始化的用法?
- boost::文件系统::recursive_directory_iterator多线程安全
- C++17 文件系统::remove_all 带有通配符路径
- 实验性文件系统库不完整C++?
- 使用文件系统时仍然需要链接到带有 C++20 的 stdc++fs?
- 无法链接文件系统库C++
- 无法识别 Mac c++ 文件系统库
- 使用Boost文件系统C++将具有特定扩展名的文件的名称保存在特定文件夹中
- 获取 clang++:错误:在编译文件系统库的代码时
- C++17 文件系统在 Windows 10 上使用 nuwen MinGW
- C++ VS 错误:<实验/文件系统>提供 std::experimental::文件系统的标头已被Microsoft弃用,将被删除
- 如果我删除指针,我的C++程序会意外删除系统文件吗?
- 如何修复 MinGW 文件系统探针?
- 将 boost::文件系统::p ath 转换为 char?
- 我可以在 ndk 中使用带有 libc++ 的实验性文件系统吗?
- 是否可以使用 std::文件系统获取根名称列表?