如何在c ++中删除文件? [英] how to delete a file in c++?

查看:68
本文介绍了如何在c ++中删除文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好吗?我想找到一种删除文件的方法吗?使用remove命令无法以简单的方式删除某些文件。像恶意软件或打开的文件。有没有可以强制删除的命令?

解决方案

要删除C ++中的文件,请使用 remove 函数来自 cstdio

  #include   <   cstdio  >  
int main(){

const < span class =code-keyword> int result = remove( C:\\Temp \\somefile.txt);
return 0 ;
}





如果失败,如结果所示,这意味着文件不存在,文件是只读的或文件由不同于执行命令的用户拥有。



如果该文件是只读的,您可以先尝试更改它(如果当前用户没有权限这也会失败),但是没有C ++本机方式来更改文件属性所以你必须使用本地安装的东西。

在Windows上,例如,尝试使用 windows.h中的 SetFileAttributes 方法(链接Kernel32)。



如果当前用户无权删除文件,则必须确保应用程序以用户身份运行谁拥有该文件或作为管理员谁可以删除它。



此外,请注意,一些恶意软件可能会使用辅助进程重新创建文件和进程,因为你kill / del如果他们处理这个问题就很困难了,而且不是C ++特有的问题。



希望这会有所帮助,

Fredrik


你可以使用删除功能

#include<< cstdio>>>

int remove(char * filename)

文件名是文件名为file的文件的路径




如果您使用的是Win32,官方的方法是将其标记为在重新启动时删除,并要求用户重新启动。要在重新引导时标记要删除的文件,请使用带有MOVEFILE_DELAY_UNTIL_REBOOT标志的MoveFileEx(将NULL作为目标)。

祝你好运


Hi everybody? I want to find a certain way to delete a file? some files cannot be deleted in a simple way with remove commands. like malwares or opened files. Is there any command that can do force delete?

解决方案

To remove a file in C++ use the remove function from cstdio.

#include <cstdio>
int main() {

    const int result = remove("C:\\Temp\\somefile.txt");
    return 0;
}



If this fails, as indicated by the result, that means the file either didn't exist, the file was read-only or the file was owned by a user different than the one executing the command.

If the file is read-only you can try first changing this (this will also fail if the current user doens't have rights to do so), but there's is no C++ "native" way of changing file attributes so you'll have to use something local to the installation your on.
On Windows for example, try using the SetFileAttributes method found in windows.h (link against Kernel32).

If the current user does not have rights to delete the file, the you must make sure the application is run as either the user who owns the file or as an administrator who can delete it.

Also, note that some malware may use a secondary process to recreate files and processes as you kill/delete them, this is a lot harder to deal with and is not a C++ specific problem.

Hope this helps,
Fredrik


you can use the remove function
#include <<cstdio>>>
int remove(char *filename)
file name is path of file with name of file


Hi,
If you are on Win32, the official way to do it is to mark it to be deleted on reboot, and ask the user to reboot. To mark the file to be deleted on reboot, use MoveFileEx with the MOVEFILE_DELAY_UNTIL_REBOOT flag (pass NULL as the destination).
good luck


这篇关于如何在c ++中删除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆