By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,347 Members | 1,325 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,347 IT Pros & Developers. It's quick & easy.

ANSI remove() and MS DeleteFile()

P: 1
Dear all,
I encounter a problem about DeleteFile() with ANSI stdio functions.
It always fails to delete file and sets ERROR_SHARING_VIOLATION.
I know I can use remove() instead of DeleteFile(), but it make me confused.
Is MS File Management Functions and ANSI stdio functions not compatible?
the code is:
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <windows.h>
  3. int main(int argc, char* argv[])
  4. {
  5.     FILE* fp = fopen("C:/testFS.txt", "wt");
  6.     fclose(fp);
  7.                 // remove("C:/testFS.txt");
  8.     if (DeleteFile(_T("C:/testFS,txt")) == 0)
  9.     {
  10.                                 // It always be here. why?
  11.         DWORD err = GetLastError();
  12.         if (err == ERROR_SHARING_VIOLATION)
  13.         {
  14.             printf("ERROR_SHARING_VIOLATION\n");
  15.         }
  16.         else
  17.         {
  18.             printf("Other error: %d\n", err);
  19.         }
  20.     }
  21.     return 0;
  22. }
Sep 14 '07 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
What compiler are you using???

Your code won't compile in Visual Studio.NET 2005. The _T macro was not defined because you did not include tchar.h. And if you are using the tchar mappings, you are using a main() instead of a _tmain().

Beyond that, your file paths have the slashes in the wrong direction. That means the file never opened (you didn't check that) and never deleted.

I fixed your code and it works fine now. There is no incompatibilty between Microsoft and ANSI C file I/O.

Here is your fixed code:
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std;
  3. #include <fstream>
  4. #include <stdio.h>
  5. #include <windows.h>
  6. #include <tchar.h>
  7. int _tmain(int argc, char* argv[])
  8. {
  9.     FILE* fp = fopen(TEXT("C:\\testFS.txt"), TEXT("wt"));
  10.     fclose(fp);
  11.                 // remove("C:/testFS.txt");
  12.     if (DeleteFile(TEXT("C:\\testFS.txt")) == 0)
  13.     {
  14.                                 // It always be here. why?
  15.         DWORD err = GetLastError();
  16.         if (err == ERROR_SHARING_VIOLATION)
  17.         {
  18.             _tprintf(TEXT("ERROR_SHARING_VIOLATION\n"));
  19.         }
  20.         else
  21.         {
  22.             _tprintf(TEXT("Other error: %d\n"), err);
  23.         }
  24.     return 0;
  25. }
  26.  
I stll didn't add the the check for fopen().
Sep 14 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.