Click here to Skip to main content
15,894,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all ,

I want to check if the file at given path exists and if it does then want to delete this it .
How can i do this .

Thnx all
Posted

You can use _stat[^] to check whether the file exists or not. If it does, then remove[^] will delete the file.

Best regards
Espen Harlinn
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 19-Nov-12 18:43pm    
Right, a 5.
--SA
Espen Harlinn 19-Nov-12 18:46pm    
Thank you, Sergey :-D
consider the following example
C++
#include <windows.h>
#include <iostream>

using namespace std;

bool exists(char* filePath)
{
	//This will get the file attributes bitlist of the file
	DWORD fileAtt = GetFileAttributesA(filePath);

	//If an error occurred it will equal to INVALID_FILE_ATTRIBUTES
	if(fileAtt == INVALID_FILE_ATTRIBUTES)
		//So lets throw an exception when an error has occurred
		throw GetLastError();

	//If the path referers to a directory it should also not exists.
	return ( ( fileAtt & FILE_ATTRIBUTE_DIRECTORY ) == 0 ); 
}

int main()
{
	if (exists("test.txt"))
		cout << "test.txt exists!\n";
	else
		cout << "test.txt does not exists!\n";

	return 0;
}</iostream></windows.h>


use this code, you can ensuare file exist or not. if it is exist
you can use
C++
CFile::Remove
 
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