I've created, and written to a file. It lets me do all of that just fine, but when I try to delete the file it says that I do not have permission. Is there something wrong with my code?:

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    char fileName[80] = "C:\\main.cpp";
    ofstream fout(fileName, ios::app);
    fout << "At the end\n";
    fout.close();
    
    ifstream fin(fileName);
    char ch;
    while(fin.get(ch))
    {
                      cout << ch;
    }
    
    if (remove(fileName) == -1)
    {
                         perror("Error deleting file: ");
    }
    else
    {
        cout << "Successful";
    }
    system("PAUSE");
    return(0);
}

I have checked to make sure the file isn't read only, which it's not.

Recommended Answers

All 7 Replies

you must close the file before it can be deleted. use fin.close() before attempting to delete it.

I've already tried that, it still gives me the error.
This also did not work:
system("del C:\main.cpp");

I ran the code. It gives error only when you try to delete the file when it is not closed. As ancient dragon mentioned you need to close the file like fin.close() before trying to remove it. I ran your code with fin.close() added and both the remove() and system("del ...") worked.

Is file you want delete still on your editor?

Do you want to delete that file. do following steps.
browse that file in explorer > right click on that file > click properties > select security tab > select advanced tab > remove all the permsions and deselect inherit from parent.

Now run the code. it will delete the file. I am trying to do this by code. let us see.

Thanks!

Hi.
Although it's no business of yours, you had better tell us your Operationg System.
Thanks.

16th Oct 2005 was the last post before moorthi showed up.
I'm sure the OP found the answer in the meantime.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.