2016-08-14 136 views
-1

我有一個寵物商店庫存程序的功能。到目前爲止,它將列出庫存,並將物品添加到庫存。現在我試圖通過它的productNumber刪除一個項目(csv文本文件中的第一個值存儲)。我改變了我的代碼,我只需要小心幫助就可以了。我需要它掃描productNumber並刪除該行的產品編號。刪除文本文件中的文本行的上下文

問題:如何獲得在文本文件中查找productNumber的條件,以便我可以刪除文本文件中的該行。

我需要一些幫助,請!我有一個設置爲以下結構的CSV文本文件:

struct inventory_s 
{ 
    int productNumber; 
    float mfrPrice; 
    float retailPrice; 
    int numInStock; 
    char liveInv; 
    char productName[PRODUCTNAME_SZ +1]; 
}; 

/*Originalfile I'm trying to copy and delete from looks like*/ 

1000,1.49,3.79,10,0,Fish Food 
2000,0.29,1.59,100,1,AngelFish 
2001,0.09,0.79,200,1,Guppy 
5000,2.40,5.95,10,0,Dog Collar Large 
6000,49.99,129.99,3,1,Dalmation Puppy 

/*function looks like*/ 

int deleteProduct(void) 
{ 

    struct inventory_s newInventory; 
    char line[50]; 
    //int del_line, temp = 1; 

    FILE* originalFile = fopen("inventory.txt", "r"); //opens and reads file 
    FILE* NewFile = fopen("inventoryCopy.txt", "w"); //opens and writes file 
    if(originalFile == NULL || NewFile == NULL) 
    { 
     printf("Could not open data file\n"); 
     return -1; 
    } 
    printf("Please enter the product number to delete:"); 
    sscanf(line," %i", &newInventory.productNumber); 

    while(fgets(line, sizeof(line), originalFile) !=NULL) 
    { 
     if (!(&newInventory.productNumber)) 
     { 
      fputs(line, NewFile); 
     } 
    } 



    fclose(originalFile); 
    fclose(NewFile); 

    return 0; 
} 



/*Input from user: 1000*/ 

/* What needs to happen in Newfile*/ 

2000,0.29,1.59,100,1,AngelFish 
2001,0.09,0.79,200,1,Guppy 
5000,2.40,5.95,10,0,Dog Collar Large 
6000,49.99,129.99,3,1,Dalmation Puppy 

回答

1

修復此類

printf("Please enter the product number to delete:"); 
int productNumber; 
scanf("%i", &productNumber); 

while(fgets(line, sizeof(line), originalFile) != NULL) 
{ 
    sscanf(line, "%i", &newInventory.productNumber); 

    if (productNumber != newInventory.productNumber) 
    { 
     fputs(line, NewFile); 
    } 
} 
+0

太謝謝你了! – RTriplett

+0

@RTriplett:請注意,你應該在代碼中添加錯誤檢查(就像你原來的那樣)。 – Olaf