文件删除操作

有两种方法:

1.DeletFile( LPCTSTR lpFileName  ); //删除的文件不会出现在回收站里面;

2.SHFileOperation(LPCTSTR lpFileName );// 删除的文件有可能出现在回收站里面(只要设置FOF_ALLOWUNDO属性);

其他注意事项:请参考下面资料中红色字体部分。

 

SHFILEOPSTRUCT

contains information that the SHFileOperation function uses to perform file operations.

typedef struct _SHFILEOPSTRUCT{

HWND hwnd;

UINT wFunc;

LPCTSTR pFrom;

LPCTSTR pTo;

FILEOP_FLAGS fFlags;

BOOL fAnyOperationsAborted;

LPVOID hNameMappings;

LPCTSTR lpszProgressTitle;

} SHFILEOPSTRUCT, *LPSHFILEOPSTRUCT;

Members

hwnd

window handle to the dialog box to diaplay information about the status of the file operation.

wFunc

value that indicates which operation to perform. This member can be one of the following values:

FO_COPY

           copy the files specified in the pFrom member to the location specified in the pTo member.

FO_DELETE

       delete the files specified in the pFrom;

FO_MOVE

       move the files specified in pFrom to the location specified in pTo;

FO_RENAME

       rename the file specified in pFrom. You cannot use the flag to rename multiple files with a single function call. Use FO_MOVE instead.

pFrom

address of a buffer to specify one or more source file names. These names must be fully qualified paths. Standard DOS wild cards, such as "*", are permitted in the file-name position. Although this  member is declared as a null-terminated string, it is used as a buffer to hold multiple file names. Each file name must be terminated by a single NULL character. An additional NULL character must be appended to the end of the final name to indicate the end of pFrom.

pTo

Address of a buffer to contain the name of  the destination file or directory. This parameter must be sent to NULL if is not used. Like pFrom, the pTo member is also a double-NULL terminated string and is handled in much the same way. However, pTo must meet the following specifications:

1.Wildcard characters are not supported.

2.copy and move operations can specify destination directories that do not exist and the system will attempt to create them. The system normally displays a dialog box to ask the user if they want to create the new directory. To suppress this dialog box and have the directories created silently, set the FOF_NOCONFIRMMKDIR flag in fFiles.

3.For copy and move operations, the buffer can contain multiple destination file names if the flags member specifies FOF_MULTIDESFILES.

4.Pack multiple names into the string in the same way as for pFrom.

5.Use only fully-qualified path names. Using relative path names will have unpredictable results.

fFlags

Flags that control the file operation. This member can take a combination of the following flags:

FlagDescription
FOF_ALLOWWUNDOPreserve Undo information,if possible. If pFrom does not contain fully qualified path and file names,this flag is ignored.
FOF_CONFIRMMOUSENot currently used.
FOF_FILESONLYPerform the operation on files only if a wildcard file name(*.*) is specified.
FOF_MULTIDESTFILESThe pTo member specifies multiple destination files (one for each source file) rather than one directory where all source files are to be deposited.
FOF_NOCONFIRMATIONRespond with "Yes to All" for any dialog box that is displayed.
FOF_NOCONFIRMMKDIRDo not confirm the creation of a new directory if the operation requires one to be created.
FOF_NO_CONNECTED_ELEMENTSVersion 5.0. Do not move connected files as a group. Only move the specified files.
FOF_NOCOPYSECURITYATTRIBSVersion 4.71. Do not copy the security attributes of the file.
FOF_NOERRORUIDo not display a user interface if an error occurs
FOF_NORECURSIONOnly operate in the local directory. Don't operate recursively into subdirectories.
FOF_RECURSEREPARSERecurse into reparse points. The default is to not recurse.
FOF_NORECURSEREPARSETreat reparse points as objects, not containers. You must set _WIN32_WINNT to 5.01 or later to use this flag. See Shell and Common Controls Versions for further discussion of versioning.
FOF_RENAMEONCOLLISIONGive the file being operated on a new name in a move, copy, or rename operation if a file with the target name already exists.
FOF_SILENTDo not display a progress dialog box.
FOF_SIMPLEPROGRESSDisplay a progress dialog box but do not show the file names.
FOF_WANTMAPPINGHANDLEIf FOF_RENAMEONCOLLISION is specified and any files were renamed, assign a name mapping object containing their old and new names to the hNameMappings member.
FOF_WANTNUKEWARNINGVersion 5.0. Send a warning if a file is being destroyed during a delete operation rather than recycled. This flag partially overrides FOF_NOCONFIRMATION.

fAnyOperationAborted

Value that receives True if the user aborted any file operations before they were completed, or FALSE otherwise.

hNameMappings

A handle to a name mapping object containing the old and new names of the renamed files. This member is used only if the fFlags member includes the FOF_WANTMAPPINGHANDLE flag. Treat hNameMapping as a pointer to a structure whose members are an UNIT value followed by a pointer to an array of SHNAMEMAPPING structure, eg:

struct HANDLETOMAPPINGS {

UINT uNumberOfMappings; // number of mappings in array LPSHNAMEMAPPING lpSHNameMapping; // pointer to array of mappings

};

The UINT value is set to the number of SHNAMEMAPPING structures in the array. Each SHNAMEMAPPING structure contains the old and new path name for one of the renamed files.

Notes: The handle must be freed with SHFreeNameMappings.

lpszProgressTitle

Address of a string to use as the title of a progress dialog box. This member is used only if fFlags includes the FOF_SIMPLEPROGRESS flag.

Remarks

If the pFrom or pTo members are unqualified names, the current directories are taken from the global current drive and directory settings as managed by the GetCurrentDirectory and SetCurrectDirectory functions.

If the pFrom is set to a file name, deleting the file with FO_DELETE will not move it the Recycle Bin,even if the FOF_ALLOWUNDO flag is set. You must use full path name.

There are two versions of this structure, an ANSI version (SHFILEOPSTRUCTA) and a Unicode version (SHFILEOPSTRUCTW). The Unicode version is identical to the ANSI version, except that wide character strings (LPCWSTR) are used in place of ANSI character strings (LPCSTR). On Windows 98 and earlier, only the ANSI version is supported. On Windows NT 4.0 and later, both the ANSI and Unicode versions of this structure are supported. SHFILEOPSTRUCTW and SHFILEOPTSTRUCTA should never be used directly; the appropriate structure is redefined as SHFILEOPSTRUCT by the pre-compiler depending on whether the application is compiled for ANSI or Unicode. SHNAMEMAPPING has similar ANSI and Unicode versions. For ANSI applications, hNameMappings points to an integer followed by an array of ANSI SHNAMEMAPPING structures. For Unicode applications, hNameMappings points to an integer followed by an array of Unicode SHNAMEMAPPING structures. However, on Windows NT 4.0 and later, SHFileOperation always returns a handle to a Unicode set of SHNAMEMAPPING structures. If you want applications to be functional with all versions of Windows, the application must employ conditional code to deal with name mappings. For example:

x = SHFileOperation(&shop);
...
if (fWin9x) {
	
	HandleAnsiNameMappings(shop.hNameMappings);
	
}
else {

	HandleUnicodeNameMappings(shop.hNameMappings);

}
 
SHFileOperation Function
copies, moves, renames, or deletes a file system object.
Syntax
int SHFileOperation(LPSHFILEOPSTRUCT lpFileOp);
Parameters
lpFileOp
[in] pointer to an SHFILEOPSTRUCT structure that contains information needs to carry out the specified operation. This parameter must contain a valid value that is not NULL.
You are responsible for validating the value. If you do not validate it, you will experience unexpected results.
Return Value
Returns zero if successful, or nonzero otherwise.
Remarks
You should use fully-qualified path names with this function, using it with relative path names is not thread safe.
With two exceptions, you cannot use SHFileOperation to move special folders from a local drive to a remote computer
by specifying a network path. The exceptions are the My Documents and My Pictures folders. (CSIDL_PERSONAL and 
CSIDL_MYPICTURES,respectively).
When used to delete a file, SHFileOperation permanently deletes the file unless you set the FOF_ALLOWUNDO flag in the
fFlags member of the SHFILEOPSTRUCT structure pointed to by lpFileOp. Setting that flag sends the file to the RecycleBin.
If you want to delete a file and guarantee that it is not placed in the Recycle Bin, use DeleteFile.
If a copy callback handler is exposed and registered, SHFileOperation calls it unless you set a flag, such as FOF_NOCONFIRMATION 
in the fFlgas member of the structure pointed by lpFileOp. See ICopyHook::CopyCallBack for details on implementing copy callback
handlers.
File deletion is recursive unless you set the FOF_NORECURSION flag in lpFileOp.
recursive /* 循環的,递归的*/
/... omitting other words.../
Minimum DLL Versionshell32.dll version 4.0 or later
Header shellapi.h
Import library shell32.lib

DeleteFile

The DeleteFile function deletes an existing file.

BOOL DeleteFile(
  LPCTSTR lpFileName
);

Parameters

lpFileName [in] Pointer to a null-terminated string that specifies the file to be deleted.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "//?/" to the path. For more information, see Naming a File.

Windows Me/98/95:  This string must not exceed MAX_PATH characters.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If an application attempts to delete a file that does not exist, the DeleteFile function fails. If the file is a read-only file, the function fails with ERROR_ACCESS_DENIED. To delete a read-only file, you must first remove the read-only attribute.

To delete or rename a file, you must have either delete permission on the file or delete child permission in the parent directory. If you set up a directory with all access except delete and delete child and the ACLs of new files are inherited, then you should be able to create a file without being able to delete it. However, you can then create a file get all the access you request on the handle returned to you at the time you create the file. If you requested delete permission at the time you created the file, you could delete or rename the file with that handle but not with any other. For more information, see File Security and Access Rights.

The DeleteFile function fails if an application attempts to delete a file that is open for normal I/O or as a memory-mapped file.

Windows Me/98/95:  The DeleteFile function deletes a file even if it is open for normal I/O or as a memory-mapped file. To prevent loss of data, close files before attempting to delete them.

To recursively delete the files in a directory, use the SHFileOperation function. To remove an empty directory, use the RemoveDirectory function.

To close an open file, use the CloseHandle function.

The DeleteFile function marks a file for deletion on close. Therefore, the file deletion does not occur until the last handle to the file is closed. Subsequent calls to CreateFile to open the file fail with ERROR_ACCESS_DENIED.

HeaderDeclared in Winbase.h; include Windows.h.
LibraryLink to Kernel32.lib.
DLLRequires Kernel32.dll.

Examples:

/* Unicode code environment */

Void MyDeleteFileFunc()

{

int nOK;
TCHAR tcBuf[256];
// 文件删除进度对话框标题;
TCHAR strTitle[]=_T("Delete File");
// 定义SHFILEOPSTRUCT结构对象;
SHFILEOPSTRUCT fileOp;
// buf 和文件操作结构体置为空;
memset(tcBuf,0,sizeof(tcBuf));
memset(&fileOp,0,sizeof(fileOp));
// 设置文件操作结构体属性;
fileOp.hwnd = this->m_hWnd;
fileOp.wFunc = FO_DELETE;
fileOp.pTo = NULL;
//此标志FOF_ALLOWUNDO使删除文件备份到Windows回收站
fileOp.fFlags = FOF_ALLOWUNDO|FOF_SILENT|FOF_NOCONFIRMATION;
fileOp.hNameMappings = NULL;
fileOp.lpszProgressTitle = strTitle;

// 只选中了一个文件,那么只需要删除一个文件

// 有默认构造函数会自动赋初值
    CString strPath;

// m_strFileName 在之前已经赋值
    if(0 == m_MediaType)
    {
         strPath.Format(_T("%s//%s"),g_Util.m_CapturePath,m_strFileName);
    }
    else if(1 == m_MediaType)
    {
        strPath.Format(_T("%s//%s"),g_Util.m_RecordPath,m_strFileName);
    }

    _tcscpy(tcBuf,strPath);

// An additional NULL character must be appended to the end of the final name to indicate the end of pFrom.

// 为字符串末尾再加上一个空格
    tcBuf[strPath.GetLength()+1] = '/0';
    fileOp.pFrom = tcBuf;
    //开始删除文件
    nOK=SHFileOperation(&fileOp);
    if (nOK)
    {
        OutputDebugString(_T("Sorry,Can not delete these file"));
        return;
    }

}


 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值