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

File locking on windows

100+
P: 180
Hi guys,,

What is wrong with below given code. It isnt locking the file???Where m I going wrong???
Expand|Select|Wrap|Line Numbers
  1. int main (){
  2.  
  3.    FILE    *pFile = NULL;  
  4.    char    *fileName = "two.txt";
  5.  
  6.    // Open the file in read mode  
  7.    pFile = fopen( fileName ,"r");   
  8.  
  9.    if (!pFile){
  10.          printf("Error opening file %s!\n", fileName);
  11.          exit(1);
  12.    }  
  13.    int beg = 0;
  14.    fseek( pFile, beg, SEEK_END  );
  15.    int end = ftell(pFile);  
  16.  
  17.    cout<<"Press <RETURN> to try to get lock: "<<endl;
  18.    getchar();
  19.    cout<<"Trying to get lock..."<<endl;
  20.  
  21.    if( !LockFile((HANDLE)pFile, end, 0, end, 0) )
  22.    {
  23.        cout<< "Cannot lock:"<<endl;
  24.        return 0;
  25.    }
  26.  
  27.    fseek( pFile, beg, SEEK_SET  );     
  28.    ifstream is(pFile);
  29.    char line[256];
  30.    while( !is.eof() ){  
  31.            is.getline( line, sizeof( line ) );  
  32.            cout<<line;  
  33.    }
  34.    cout<<"Press <RETURN> to release lock: "<<endl;
  35.    getchar();
  36.    UnlockFile((HANDLE)pFile, 0, 0, end, 0);
  37.    cout<<"Unlocked.\n"<<endl;    
  38.    fclose( pFile );
  39.  
  40.    return 0;  
  41.  }
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...
May 24 '07 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
I don't believe LockFile prevents reading from a mapped file view.

You may need to build a semaphore class to prevent reading.
May 24 '07 #2

Post your reply

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