C++: Delete a File

Bjarne-stroustrup
 

C++ delete file and directory examples must be read with particular attention to their paths. The preserved program demonstrates file removal and a platform-specific empty-directory operation. Its root-style targets are historical task examples, not instructions to run against an important filesystem.

C++ delete file and directory: reading the example

Removing a file name is different from recursively deleting a directory tree. The directory operation shown is intended for an empty directory. Relative names use the process’s working directory, while root-style paths follow operating-system-specific rules. Neither is guaranteed to refer to the source folder.

If adapting the example, use a dedicated disposable test directory, inspect resolved target paths and check each return value. Test absence and permission failure as separate cases. A program reaching its final return doesn’t establish that every removal succeeded.

Assumptions and limits of C++ delete file and directory

direct.h and _rmdir are Microsoft-specific, and the example provides no comprehensive error handling or recovery. Existence can change between a check and removal. Keep any recursive deletion out of this small exercise unless its scope and path validation are deliberately designed. The original code is preserved without being executed in this pass.

For the relevant definitions, consult the reference documentation. The explanation here does not claim that every preserved legacy fragment compiles unchanged.

Preserved original example

In this task, the job is to delete a file called “input.txt” and delete a directory called “docs”. This should be done twice: once “here”, i.e. in the current working directory and once in the filesystem root.

#include <cstdio>
#include <direct.h>

int main() {
	remove( "input.txt" );
	remove( "/input.txt" );
	_rmdir( "docs" );
	_rmdir( "/docs" );

	return 0;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.