Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

i made a function that first reads the file and checks if it exists or not and then it removes it after a confirmation but if i do directly like

remove("a.text");

it deletes the file that has the name a.txt but when i use my function

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();
    }

it only checks the filename but does not delete it.

like image 650
Akhilesh Sharma Avatar asked Apr 16 '17 17:04

Akhilesh Sharma


People also ask

What is remove () in C?

The remove function in C/C++ can be used to delete a file. The function returns 0 if files is deleted successfully, other returns a non-zero value. #include<stdio.h> int main() {

How do I delete all contents of a file in C?

If the file is already open you can use freopen() function from stdio. h with "w" mode as it will first close the file and then reopen it for writing erasing whatever was in the file previously.

Which syntax is used to delete?

Syntax: rm command to remove a file -f : Forcefully remove file.


3 Answers

In c++17 we have the filesystem library, which gives the tools to easily deal with the problem.

Example:

#include <filesystem>
#include <iostream>
#include <string>

int main()
{
  std::string searchfilename;
  std::cout << "Please enter the filename to be searched\n";
  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';
  }
}
like image 167
francesco Avatar answered Oct 15 '22 16:10

francesco


You forgot closing the file that you have opened. So, CLOSE the file and it should work.

Note: The solution worked for @AkhileshSharma and included the comment as an answer to close the question as answered.

like image 20
The Apache Avatar answered Oct 15 '22 15:10

The Apache


When you try to delete a file, you should always handle the return value of remove function immediately. For successful result it returns 0 and for failed, it returns non-zero.

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

remove is in the stdio.h file
and strerror is in the string.h

So after your remove function, check to see for what reason it has not been deleted.
The error number is stored in errno variable and strerror can map the error number to a string that tells the reason of failure.


Also you can test the error code and a Linux Terminal if you have it using perror command

> 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
like image 37
Shakiba Moshiri Avatar answered Oct 15 '22 14:10

Shakiba Moshiri