2012-12-14 25 views
1

我有這個問題。我有一個C++程序;該程序成功地創建了我保存記錄的文件。在一個過程中,我編輯一個記錄並製作另一個具有不同名稱的文件。最後我關閉這兩個文件,當我嘗試刪除舊的和重新命名新我有這樣的錯誤:權限被拒絕時,我使用刪除()

Error deleting file: Permission denied.

void SoldDevices() 
{ 
int soldQuantity = 0; 
char soldModel[20]; 
ElShop tempVar; 
FILE *newFile; 

printf("Enter model of sold device: "); 
gets(soldModel); 

file = fopen(fileName, "r+"); 
fread(&shop, sizeof(shop), 1, file); 

while (!feof(file)) 
{ 
     if (strcmp(shop.model, soldModel) == 0) 
     { 
      tempVar = shop; 
      break; 
     } 

     fread(&shop, sizeof(shop), 1, file); 
} 

fclose(file); 

printf("Enter how much devices are sold: "); 
scanf("%d", &soldQuantity); 

while (tempVar.quantity < soldQuantity) 
{ 
     printf("No items available!\n"); 
     printf("Enter how much devices are sold: "); 
     scanf("%d", &soldQuantity); 
} 

tempVar.quantity = tempVar.quantity - soldQuantity; 
printf("%d\n", tempVar.quantity); 

file = fopen(fileName, "rb"); 
newFile = fopen("New", "wb"); 

fread(&shop, sizeof(shop), 1, file); 

while (!feof(file)) 
{ 
     if(strcmp(soldModel, shop.model) == 0) 
     { 
      fwrite(&tempVar, sizeof(shop), 1, newFile); 
     } 
     else 
     { 
      fwrite(&shop, sizeof(shop), 1, newFile); 
     } 

     fread(&shop, sizeof(shop), 1, file); 
} 
fclose(newFile); 
fclose(file); 

if(remove(fileName) != 0) 
    perror("Error deleting file"); 
else 
    puts("File successfully deleted"); 
rename("New", fileName); 
} 

有沒有人有一些想法來解決這個問題?

+1

您有足夠的權利嗎? – Link

+0

您是否嘗試使用命令行或文件資源管理器刪除相同的文件? – yasouser

+0

你在使用什麼操作系統? –

回答

1

我曾經有過和你一樣的問題,但現在我已經解決了它。 當你使用remove()時,你必須有一些文件指針沒有關閉。它不必位於相同的.cpp文件中,也可以位於不同的文件中。

以我爲例,我想我已經關閉了這個文件,但是後來我發現我在fclose()之前有「返回」句子,導致文件沒有正確關閉。

PS: 1.我有3個.cpp文件。

  1. 包含remove()的文件在沒有正確關閉文件的文件(A.cpp)之後使用。

  2. 因爲A.cpp沒有正確關閉文件,所以會出現Permission Denied。

  3. 我的英文很差。希望這可以幫到你。