Click here to Skip to main content
15,918,031 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
hello
how can I delete a file/folder with C++?

how can I overwrite a file/folder with C++?

thanks :)
Posted
Updated 7-Mar-11 6:05am
v2

(assuming using Windows)

delete : ShFileOperation
overwrite file : just create a file with the same name as the original one and handle all the errors that can happen when the file exists.
overwrite folder : maybe the same thing as above but with difficulty if the folder is not empty?
 
Share this answer
 
Comments
Dalek Dave 7-Mar-11 10:55am    
Good Call.
For Deletion, use one of the following:
remove
_tremove(cpFileName)
DeleteFile(cpFileName)

For overwriting a file, open the file with the truncate mode using one of the following:
fopen(cpFileName,_T("wb"))
_tfopen(cpFileName,_T("wb"))
::CreateFile(caFileName,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_ARCHIVE,NULL);
 
Share this answer
 
There are yet another ways of doing these.

In Windows API.
To delete a file:
BOOL WINAPI DeleteFile(LPCTSTR lpFileName);

To remove a folder:
BOOL WINAPI RemoveDirectory(LPCTSTR lpPathName);

Using standard C libs: (portable)
To delete a file:
int __cdecl remove(const char*); // stdio.h or io.h
int __cdecl _unlink(const char*); // stdio.h or io.h

To remove a folder:
int __cdecl rmdir(const char*); // io.h or direct.h

To delete a file or folder, its read-only attribute must be removed and it's not in use. And folders must be empty, of course.

To overwrite a file needs some more work. It should be opened for writing and should be written from the beginning to the end with some data (whatever you wish) over every byte. Because deleting a file only marks it as deleted and logically removed from the file system, all the data belonging to the file will be retained on disk (up to being overwritten by another disk operation). Deleting a file and creating a new one with the same name may (or may not) write over its directory entry, not over the whole file data.

Main advantage of ShFileOperation() over above is ability to operate recursively into sub folders.
 
Share this answer
 
Thanks .... try them ...

and another questions:


I have two questions. My first one is, that how can i "put" something into the default windows right click pop-up menu? I mean, if i click with the right mouse button on an .exe, then the default things appers(like cut, copy, send to, run as...), but how can i put there one extra line, like "MyApp", which will start my application? I want to do all this in c++. My second question is, how can i get the filename (or the full path) on which i have started MyApp from the pop-up menu?

Thank in advance!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900