File locking on windows

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vermarajeev
    New Member
    • Aug 2006
    • 180

    File locking on windows

    Hi guys,,

    What is wrong with below given code. It isnt locking the file???Where m I going wrong???
    Code:
    int main (){
      
       FILE    *pFile = NULL;  
       char    *fileName = "two.txt";
      
       // Open the file in read mode  
       pFile = fopen( fileName ,"r");   
    
       if (!pFile){
             printf("Error opening file %s!\n", fileName);
             exit(1);
       }  
       int beg = 0;
       fseek( pFile, beg, SEEK_END  );
       int end = ftell(pFile);  
    
       cout<<"Press <RETURN> to try to get lock: "<<endl;
       getchar();
       cout<<"Trying to get lock..."<<endl;
    
       if( !LockFile((HANDLE)pFile, end, 0, end, 0) )
       {
    	   cout<< "Cannot lock:"<<endl;
    	   return 0;
       }
    
       fseek( pFile, beg, SEEK_SET  );     
       ifstream is(pFile);
       char line[256];
       while( !is.eof() ){  
               is.getline( line, sizeof( line ) );  
               cout<<line;  
       }
       cout<<"Press <RETURN> to release lock: "<<endl;
       getchar();
       UnlockFile((HANDLE)pFile, 0, 0, end, 0);
       cout<<"Unlocked.\n"<<endl;    
       fclose( pFile );
       
       return 0;  
     }
    Hi Banfa, can you please help me with this. I want to lock a file on windows (Microsoft Visual Studio .NET 2003) such that other processes are unable to read the same file again. Please help...
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    I don't believe LockFile prevents reading from a mapped file view.

    You may need to build a semaphore class to prevent reading.

    Comment

    Working...