2016-10-02 75 views
0

我寫了這個函數來刪除fguest文件的記錄。它會工作幾次,但幾次嘗試後,它開始顯示Permission denied ..我無法弄清楚這是什麼原因,有誰可以告訴我是什麼原因?權限被拒絕時重命名.dat文件在C

void delResPer(void) 
{ 
    int recFound; 
    char status[50] = " ResDeleted "; 

    printf("\nPlease enter Guest's ID to search: "); 
    if(scanf("%s",&search) != 1) 
    { 
     invalidInput(); 
     flushStdin(); 
     editRes();  
    } 
    flushStdin(); 

    fguest = fopen(guestFile,"rb"); 
    if (fguest == NULL) 
    { 
     printf("Unable to locate guestFile\n\n"); 
     returnToMain(); 
    } 
    while(fread(&grec,sizeof(GUEST),1,fguest)==1)   
    { 
     if (strcmp(grec.id,search)==0)       
     { 
      printf("\n\n\nRecord found: \n"); 
      printf("\nGuest\'s ID\t\t: %s",grec.id); 
      printf("\nGuest\'s Name\t\t: %s",grec.name);   
      printf("\nRoom\'s Type\t\t: %d",grec.r_type); 
      checked(grec.r_type); 
      recFound = 1; 
     } 
    } 


    if (recFound != 1) 
    { 
     printf("No matching record found..\n"); 
     printf("Please retry with a valid record..\n"); 
     printf("Page is refreshing.."); 
     Sleep(500); 
     editRes(); 
    } 

    else if (recFound == 1) 
    { 
     printf("\n\nDelete the record (Y/N)?"); 
     cfm = getchar(); 
     flushStdin(); 
     if (cfm == 'Y' || cfm == 'y') 
     { 
      ftemp = fopen(tempFile,"wb+");        
      rewind(fguest); 
      while(fread(&grec,sizeof(grec),1,fguest)==1)  
      { 
       if (strcmp(grec.id,search)!=0)     
       { 
        fseek(ftemp,0,SEEK_CUR);     
        fwrite(&grec,sizeof(grec),1,ftemp);  
       } 
      } 
      fclose(fguest); 
      fclose(ftemp); 
      if(remove(guestFile)!=0) 
      { 
       errnum = errno; 
       fprintf(stderr,"Failed to remove guestFile :: %s\n",strerror(errnum)); 
       Sleep(500); 
       //printf("Program is exiting.."); 
       //return; 
      } 
      if(rename(tempFile,guestFile)!=0) 
      { 
       errnum = errno; 
       fprintf(stderr,"Failed to rename guestFile :: %s\n",strerror(errnum)); 
       Sleep(500); 
       printf("Program is exiting.."); 
       return; 
      } 
      if (check == 1) 
       SpDeluxe++; 
      else if (check == 2) 
       Deluxe++; 
      else if (check == 3) 
       Premium++; 
      else if (check == 4) 
       Basic++; 
      refreshRoomAvail(); 
      printf("Record is deleted successfully..\n"); 
      Sleep(250); 
      returnToMain(); 
     } 

     else if (cfm == 'N' || cfm == 'n') 
     { 
      printf("Deletion of record is cancelled\n"); 
      printf("Page is refreshing.."); 
      Sleep(500); 
      editRes();          
     } 

     else 
     { 
      invalidInput(); 
      editRes();           
     } 
    }             
} 

回答

1

您正在用完文件句柄。

fguest在您的功能的頂層打開,但只在cfm == 'Y' || cfm == 'y'的分支中關閉。如果未滿足該條件,或者該代碼從未達到(例如recFound != 1),則該文件保持打開狀態。

您需要總是在函數退出前關閉文件。

+0

ohhh我明白了!它在我將'fclose(fguest)'添加到'recFound!= 1'後運行正常,'cfm =='n'|| cfm =='N''和'else' –