Checking the File is write Protected (Read only) – VC++ MFC

Here is a code to check the file is read-only (i.e Write protected) or not and changing the attribute of file if it is read-only.

 

Pass the file name or file path along with file name to this function. Ask the user to overwrite the file. If β€˜yes’ change the attribute of the file to overwrite the file. If β€˜No’ return from the function without changing the attributes.

 

#define  ERR_FILEWRITEPROTECTED "The file is read only, would you like to overwrite"

#define  ERR_FILEWRITEPROTECTED_CAPTION "Read Only File"

 

BOOL Write_Protected_File(CString strFileName)

{

      DWORD dwAttr;

      CString strErrText;

      WIN32_FIND_DATA FindFileData;

      HANDLE hFind;

 

      hFind = FindFirstFile(strFileName, &FindFileData);

 

      dwAttr = GetFileAttributes(strFileName);

 

if( (dwAttr & FILE_ATTRIBUTE_READONLY) && (hFind != INVALID_HANDLE_VALUE) )

      {

            strErrText.Append(ERR_FILEWRITEPROTECTED);

            strErrText.Append(" '");

            strErrText.Append(strFileName);

            strErrText.Append("' ?");

 

int nClck = MessageBox(NULL, strErrText,ERR_FILEWRITEPROTECTED_CAPTION,MB_ICONWARNING|MB_YESNO);

            if(nClck == CONST_Y)

            {

                  SetFileAttributes(strFileName,dwAttr & 0xfffffffe);

                  return TRUE;

            }

            else

                  return FALSE;

      }

      else

            return TRUE;

}