Hi all,
Can any one tell me how to delete any file from a C++ code. I can do it with the help of the function 'system()', but is there any other way? :?: :?: :?:

Dani AI

Generated

The quick path forward: on modern compilers use the C++17 filesystem API for a portable, well‑behaved delete. On POSIX use the unlink call when you need a tiny dependency, and on Windows use the Win32 DeleteFile API when you must interact with the platform directly. originally asked about calling the shell; pointed out the standard C routine — below are safer, more explicit alternatives and a few run‑time cautions.

Example (portable C++17, non‑throwing form):

#include <filesystem>
#include <system_error>

std::error_code ec;
if (std::filesystem::remove("path/to/file", ec)) {
// file removed
} else if (ec) {
// handle error: ec.message()
} else {
// file did not exist
}

For POSIX systems, use unlink and check errno for details. It removes the directory entry immediately; the actual storage is freed when the last file descriptor is closed. See the man page for details: unlink(2).

On Windows, use DeleteFile and GetLastError() to inspect failure reasons (file locked, permission, path syntax); you may need to clear read‑only attributes first with SetFileAttributes. See the Microsoft docs: DeleteFileA / DeleteFileW.

Practical tips: prefer attempting the delete and handling errors rather than a separate "exists then delete" check (avoids TOCTOU races). Use the filesystem API when portability and expressive error reporting matter; use platform APIs when you need platform-specific behavior (like interacting with Windows recycle bin, locking semantics, or fine‑grained attributes). For C++17 details and overloads, see the reference for std::filesystem: std::filesystem (C++ reference).

Recommended Answers

All 2 Replies

int remove (const char *filename)

It's a C function for removing a file, declared in stdio.h.

Thanks a lot for this answer.

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.