#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct order{
char name[1000];
int price;
struct order *next;
} LIST;
void remove_node(LIST *start, const char *del_name)
{
LIST *prev = start;
while (prev->next)
{
LIST *p = prev->next;
if (strcmp(p->name, del_name) == 0)
{
LIST *next = p->next;
free(p);
prev->next = next;
} else {
prev = prev->next;
}
}
}
void del_name_write(LIST *node, const char *filename, const char *del)
{
FILE *fp;
if(node == NULL ){
return;
}
if((fp = fopen(filename, "w")) == NULL){
fprintf(stderr, "Could not open file\n");
exit(1);
}
remove_node(node, del);
printf("-----削除後-----\n");
for (LIST *tmp = node; tmp; tmp = tmp->next) {
printf("%s, %d\n", tmp->name, tmp->price);
}
// ファイルセーブってどうするんですか?
fclose(fp);
}
LIST *file_read(const char *filename){
FILE *fp;
LIST data;
LIST *start = NULL,*tmp;
if((fp=fopen(filename,"r")) == NULL)
{
fprintf(stderr, "Could not open file\n");
exit(1);
}
while(1)
{
if(feof(fp) != 0){
break;
}
if(fscanf( fp, "%s%d", &data.name, &data.price)==0){
break;
}
if(start == NULL){
start=(LIST *)malloc(sizeof(LIST));
tmp=start;
}else{
tmp->next=(LIST *)malloc(sizeof(LIST));
tmp=tmp->next;
}
memcpy(tmp,&data,sizeof(LIST));
tmp->next=NULL;
}
fclose(fp);
// List表示
for (tmp = start; tmp; tmp = tmp->next) {
printf("%s, %d\n", tmp->name, tmp->price);
}
return start;
}
void list_free(LIST **pstart)
{
LIST *p = (*pstart)->next;
while (p) {
LIST *next = p->next;
free(p);
p = next;
}
free(*pstart);
*pstart = NULL;
}
int main(void)
{
char *p=(char *)malloc(10*sizeof(char));
LIST *file_list;
printf("削除したい商品名を入力する:");
scanf("%s",p);
printf("\n");
file_list = file_read("test_1.txt");
del_name_write(file_list,"test_2.txt",p);
list_free(&file_list);
free(p);
return 0;
}