2017-04-16 183 views
1

我犯了一個函數,首先讀取該文件,並檢查它是否存在與否,然後確認之後刪除它,但一個文件,如果我直接不喜歡如何刪除文件處理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

這不是,這就是爲什麼我只寫評論。 –

回答

0

您忘記關閉已打開的文件。 因此,關閉文件,它應該工作。

注意:該解決方案爲@AkhileshSharma工作,並將該評論作爲回答關閉問題的答案。

0

當你試圖刪除一個文件,你應該總是處理輸出就地這樣的:

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說,我沒有關閉文件之前刪除()所以我想,這是真正的問題 –