我有宠物商店库存程序的功能。到目前为止,它将列出库存,并将项目添加到库存中。现在我正在尝试通过其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
答案 0 :(得分: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);
}
}