views:

200

answers:

3
+2  Q: 

C++ delete file

When I compile and run my C++ program that deletes a file called example.txt (below)

#include <stdio.h>

int main ()
{
  if( remove( "example.txt" ) != 0 )
    perror( "Error deleting file" );
  else
    puts( "File successfully deleted" );
  return 0;
}

It comes out like this...

cd c:\Users\Mark\Desktop  
C:\Users\Mark\Desktop>app.exe  
Error deleting file: Permission denied  

I lifted all restrictions on the file and there is full access to anyone (that should include my program).

Any solutions?

EDIT

When I type in del example.txt on command prompt it works.

Weird...

A: 

Mark, SB is asking if some other program has opened / locked example.txt ... say if you have notepad open to (re-)create that file.

jdu.sg
No nothing open to edit it with, this is a confusing problem :P
Mark
+1  A: 

I guess remove() takes the path as a parameter. So we need to specify the entire path as a parameter for remove function.

eg: remove("home/xxx/example.txt");

Teja
+1  A: 

You are giving the exact same example listed in Cplusplus so, if the program doesn't work, I think it is an O.S Related problem.

If you are using windows 2k or greater, try the DeleteFile api and look if the same error happens.

I can't add comments to the question, so, sorry if this isn't a proper answer.

Be sure you don't have the file opened. Try creating a new file from your program and deleting it.

Marco