Delete a file with C++

matchz
matchz used Ask the Experts™
on
Hi experts,

I have a very simple question. How can I delete a file (say, c:\temp\hello.txt) with C++?
Is it any internal function other then system can do that?

Thank you.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
You can use remove() function.

Commented:
int remove( const char *path );

The remove function is part of the C/C++ standard.

If you want to use a non-C/C++ function you can use the DeleteFile() function which is an OS specific functions.

Commented:
In Windows, the WINAPI function RemoveFile() is a better alternative then the ansi C function remove().  This is how to use it:

#include <windows.h>  // only if NOT MFC project...

BOOL DeleteFile(
  LPCTSTR lpFileName   // file name
);

Returns nonzero if successfull. Otherwise, error number can be retrieved from ::GetLastError()

On Win9x, the file is removed even if it is opened for IO.  On NT, you can only delete a file that is non-readonly and is not in use (and if you have access to it)

Best Regards,
Tim Musschoot
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

Commented:
>>In Windows, the WINAPI function RemoveFile()
timussch,
It's not called RemoveFile.  It's DeleteFile.
Furthermore, that is what I already suggested for a non-C/C++ method in my previous comment.

Commented:
yep, was a little mistypingerror...
use remove(char *path)
in stdio.h
or
unlink(char *path) in dos.h

Commented:
FYI:
>>unlink(char *path) in dos.h
unlink is a OS specific function, and it's not part of the C++ standard.

On platforms that do support unlink, unlink's behavior is not the same.

>>use remove(char *path)
I already mention the remove suggestion in the first two comments.

Author

Commented:
Hi experts, Thank you for your comments. They really help me a lot. For the problems of standard, I think both remove() and remvoefile() are ok for me. However, in some cases, i would like the standard method if both of them provide the similar result.

Thank you very much.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial