Ok i want to rename a file example:
C://test.txt to C://new.txt

Dani AI

Generated

Quick summary: the C runtime rename() is the simplest solution (as pointed out), but a few practical points make it work reliably in Visual C++ 6.0: use properly-escaped paths, be aware of file locks and permissions, and choose a Win32 API when overwriting or atomic behavior is required.

Path and escaping: in C string literals backslashes must be escaped, e.g. C:\\test.txt. Absolute paths avoid surprises with the current working directory. Many CRT functions accept forward slashes, but backslashes are conventional on Windows.

Common failure causes and fixes: the call will fail if the source file is still open by the same process or another program (editor, Explorer preview, antivirus). Permissions or read-only attributes will also block a rename. If the destination already exists, rename() on Windows typically fails — options are to remove the destination first (with caution) or use the Win32 API to replace it.

Win32 alternative (overwrite support): MoveFileEx can replace an existing file atomically. Example:

#include <windows.h>

if (!MoveFileExA("C:\\test.txt", "C:\\new.txt", MOVEFILE_REPLACE_EXISTING)) {
    DWORD err = GetLastError();
    printf("MoveFileEx failed: %lu\n", err);
}

Error handling: rename() returns 0 on success; on failure check errno and use perror() for a message. For Win32 calls use GetLastError(). Typical errno values to inspect are ENOENT (source missing), EACCES/EPERM (permission/lock), and EEXIST (destination exists).

Practical checklist that complements ’s example and answers ’s request: escape backslashes, close any open handles, confirm paths and permissions, check return codes and diagnostics, and consider MoveFileEx when overwriting or requiring atomic replace.

Recommended Answers

All 2 Replies

int rename( const char *oldname, const char *newname );

Here is an Example

/* rename example */
#include <stdio.h>

int main ()
{
int result;
char oldname[] ="oldname.txt";
char newname[] ="newname.txt";
result= rename( oldname , newname );
if ( result == 0 )
puts ( "File successfully renamed" );
else
perror( "Error renaming file" );
return 0;
}

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.