如何在 C++ 中的文件处理中删除文件

How to delete a file in file handling in c++

本文关键字:文件 处理 删除 C++      更新时间:2023-10-16

>我做了一个函数,首先读取文件并检查它是否存在,然后在确认后将其删除,但如果我直接喜欢

remove("a.text");

它删除了名为 a 的文件.txt但是当我使用我的函数时

int deletediary()
{
    string searchfilename;
    cout<<"nPlease enter the filename to be searchedn";
    cin>>searchfilename;
    searchfilename.append(".txt");
    fileread.open(searchfilename.c_str());
    if(!fileread){
        cout<<"nERROR :Either you didn't enter an invalid date or you entered an date with no entrynn";
        A :
        cout<<"Continue to search? (y/n)n";
        if(getch()=='y')
        {
            modifydiary();
        }
        else if(getch()=='n')
        {
            menuview();
        }
        else 
        {
            cout<<"Enter Correct Optionn";
            goto A;
        }
    }
    else{
        system("cls");
        int i;
        B :
        cout<<"Are you sure you want to remove this diary entry? (y/n)";
        if(getch()=='y')
        {
            remove(searchfilename.c_str());
        }
        else if(getch()=='n')
        {
            menuview();
        }
        else 
        {
            cout<<"Enter Correct Optionn";
            goto B;
        }   
        cout<<"INFO :Deleted!!!";
        system("pause");
        menuview();
    }

只检查文件名,但不删除它。

c++17我们有文件系统库,它提供了轻松处理问题的工具。

例:

#include <filesystem>
#include <iostream>
#include <string>
int main()
{
  std::string searchfilename;
  std::cout << "Please enter the filename to be searchedn";
  std::cin >> searchfilename;
  try {
    if (std::filesystem::remove(searchfilename))
       std::cout << "file " << searchfilename << " deleted.n";
    else
       std::cout << "file " << searchfilename << " not found.n";
  }
  catch(const std::filesystem::filesystem_error& err) {
     std::cout << "filesystem error: " << err.what() << 'n';
  }
}

您忘记关闭已打开的文件。因此,关闭文件,它应该可以工作。

注意:该解决方案适用于@AkhileshSharma,并将注释作为答案包含在内,以关闭已回答的问题。

当您尝试删除文件时,应始终立即处理 remove 函数的返回值。对于成功的结果,它返回0,对于失败,它返回非零。

const int result = remove( "no-file" );
if( result == 0 ){
    printf( "successn" );
} else {
    printf( "%sn", strerror( errno ) ); // No such file or directory
}

removestdio.h文件中
strerrorstring.h

因此,在remove函数之后,请检查它未被删除的原因。
错误号存储在变量errno strerror可以将错误号映射到指示失败原因的字符串。


您也可以使用以下命令测试错误代码和 Linux 终端perror

> perror 0
OS error code   0:  Success
> perror 1
OS error code   1:  Operation not permitted
> perror 2
OS error code   2:  No such file or directory
> perror 3
OS error code   3:  No such process
> perror 4
OS error code   4:  Interrupted system call
> perror 5
OS error code   5:  Input/output error
这是

删除文件的另一种简单方法

//complete location of file with path
std::string fileLocStr;
fileLocStr.append("C:temptest.txt");
//create dos command to delete file
std::string delFileCmd = "del /s /q " + fileLocStr;
cout << "delFileCmd: " << delFileCmd << endl;
//this executes the command
int delFileStatus = system(delFileCmd.c_str());
//you have to give the path of the file for example(path="C:\data\newfolder")
       System::IO::DirectoryInfo^  directory = gcnew System::IO::DirectoryInfo(path);
       for each(System::IO::FileInfo^ file in directory->GetFiles())
       {
       //for getting the extension of file(if you want to delete specific extension file)
       String^ s = file->Extension;
       if (file->Extension == ".png")
       {
        file->Delete();
       }
       }