使用CreateFile函数创建文件会导致写保护文件

时间:2014-12-05 06:16:49

标签: c++ visual-studio-2010 visual-c++

我一直在尝试在 SHGetFolderPath 返回的路径中编写文件。但是在创建文件时,它已被赋予写保护。以下是我的代码:

#include <Windows.h>
#include <Shlobj.h>
#include <iostream>
#include <Shlwapi.h>

int main()
{
    HANDLE hfile;
    TCHAR szPath[MAX_PATH];
    char dataBuffer[] = "Some data to write here";
    DWORD dwBytesWritten = 0;
    if(SUCCEEDED(SHGetFolderPath(NULL,CSIDL_COMMON_APPDATA,NULL,0, szPath)))    
    {
        std::cout << szPath << std::endl;
        PathAppend(szPath,TEXT("lpa"));
        std::cout << szPath << std::endl;
        PathAppend(szPath,TEXT("config"));
        std::cout << szPath << std::endl;
        CreateDirectory(szPath, NULL);
        PathAppend(szPath, TEXT("lpa.config"));
        std::cout << szPath << std::endl;
        hfile = CreateFile(szPath,GENERIC_READ|GENERIC_WRITE,0,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);
        /*WriteFile(hfile,dataBuffer,(DWORD)strlen(dataBuffer),&dwBytesWritten,NULL);
        std::cout << szPath <<std::endl;*/
    }

}

代码在 C:\ ProgramData \ lpa \ config \ lpa.config 中创建一个文件,但编辑该文件弹出对话框,说明WriteProtection。我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

是,当您使用管理员权限运行VS实例时,会为创建的文件分配特殊权限。以非管理员身份运行程序或使用SECURITY_DESCRIPTOR,以便其他用户可以访问该文件。

Creating a Security Descriptor for a New Object in C++

链接中的示例显示了如何创建注册表项,您可以改为使用CreateFile()。

答案 1 :(得分:0)

我使用 CSIDL_LOCAL_APPDATA 代替 CSIDL_COMMON_APPDATA 解决了这个问题。我有如下修改后的代码:

#include <Windows.h>
#include <Shlobj.h>
#include <iostream>
#include <Shlwapi.h>

int main()
{
    HANDLE hfile;
    TCHAR szPath[MAX_PATH];
    char dataBuffer[] = "Some data to write here";
    DWORD dwBytesWritten = 0;
    if(SUCCEEDED(SHGetFolderPath(NULL,CSIDL_LOCAL_APPDATA,NULL,0, szPath))) 
    {
        std::cout << szPath << std::endl;
        PathAppend(szPath,TEXT("lpa"));
        if(!CreateDirectory(szPath, NULL))
        {
            std::cout << "Create directory failed" <<std::endl;
        }
        std::cout << szPath << std::endl;
        PathAppend(szPath,TEXT("config"));
        if(!CreateDirectory(szPath, NULL))
        {
            std::cout << "Create directory failed" <<std::endl;
        }
        std::cout << szPath << std::endl;
        PathAppend(szPath, TEXT("lpa.config"));
        std::cout << szPath << std::endl;
        hfile = CreateFile(szPath,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);
        WriteFile(hfile,dataBuffer,(DWORD)strlen(dataBuffer),&dwBytesWritten,NULL);
        std::cout << szPath <<std::endl;
    }

}