gpt4 book ai didi

c - 根据上下文删除文本文件中的一行文本

转载 作者:行者123 更新时间:2023-11-30 19:11:50 26 4
gpt4 key购买 nike

我有一个宠物店库存程序的函数。到目前为止,它将列出库存,并向库存添加一个项目。现在我试图按产品编号(csv 文本文件中的第一个值存储)删除项目。我改变了我的代码,我只需要一点帮助来解决这个问题。我需要它来扫描产品编号并按产品编号删除该行。

问题:如何获得在文本文件中查找产品编号的条件,以便我可以删除文本文件中的该行。

我需要一些帮助!我有一个 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

最佳答案

像这样修复

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);
}
}

关于c - 根据上下文删除文本文件中的一行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38945991/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com