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

问题描述:

我犯了一个函数,首先读取该文件,并检查它是否存在与否,然后确认之后删除它,但一个文件,如果我直接不喜欢如何删除文件处理C++中

remove("a.text"); 

它会删除其名称a.txt中的文件,但是当我用我的功能

int deletediary() 
{ 
    string searchfilename; 
    cout<<"\nPlease enter the filename to be searched\n"; 
    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 entry\n\n"; 
     A : 
     cout<<"Continue to search? (y/n)\n"; 
     if(getch()=='y') 
     { 
      modifydiary(); 
     } 
     else if(getch()=='n') 
     { 
      menuview(); 
     } 
     else 
     { 
      cout<<"Enter Correct Option\n"; 
      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 Option\n"; 
      goto B; 
     } 
     cout<<"INFO :Deleted!!!"; 
     system("pause"); 
     menuview(); 
    } 

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

+1

避免转到并使用std :: filesystem –

+0

但我如何使用goto与remove()函数相关? –

+0

这不是,这就是为什么我只写评论。 –

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

注意:该解决方案为@AkhileshSharma工作,并将该评论作为回答关闭问题的答案。

当你试图删除一个文件,你应该总是处理输出就地这样的:

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

remove是在stdio
strerror是在后string.h

所以你remove功能检查,看看它没有被删除的原因。

+1

是的,我在之前的代码中添加了stdio,但它仍然没有工作,但作为@TheApache说,我没有关闭文件之前删除()所以我想,这是真正的问题 –