#include<stdio.h>
#include<stdlib.h>
struct hardware{
int rec;
char tool[100];
int quantity;
int cost;
};
struct hardware get_hardware(int n)
{
struct hardware hw;
while(getchar() != '\n');
printf("Enter Record [%d] : ", n);
scanf("%d", &hw.rec);
printf("Enter Tool Name [%d]: ", n); getchar();
scanf("%[^\n]", hw.tool); getchar();
printf("Enter Quantity [%d]: ", n);
scanf("%d", &hw.quantity);
printf("Enter Cost [%d] : ", n);
scanf("%d", &hw.cost);
return hw;
};
struct hardware *get_hardware_array(int count)
{
struct hardware *hw = (struct hardware *)malloc(sizeof(struct hardware) * count);
for (int i = 0; i < count; i++){
hw[i] = get_hardware(i + 1);
}
return hw;
};
void change_line(char*filename, struct hardware hw, int line)
{
FILE *file = fopen(filename, "r");
FILE *temp = fopen("temp.txt", "w");
int i = 1;
char buffer[256];
while (fgets(buffer, 256, file))
{
if (i++ == line)
fprintf(temp, "%d %s %d %d\n", hw.rec, hw.tool, hw.quantity, hw.cost);
else
fputs(buffer, temp);
}
fclose(file);
fclose(temp);
remove(filename);
rename("temp.txt", filename);
}
void update_hardware(char*filename, struct hardware *hw, int count)
{
FILE *file = fopen("hardware.txt" , "a");
fprintf(file,"\tRecord # \tTool name \tQuantity \tCost");
for (int i = 0; i < count; i++)
fprintf(file, "\t%d \t%s \t%d \t%d\n", hw[i].rec, hw[i].tool, hw[i].quantity, hw[i].cost);
fclose(file);
}
void remove_line(char *filename, int line)
{
FILE *file = fopen(filename, "r");
FILE *temp = fopen("temp.txt", "w");
char buff[256];
int i = 1;
while (fgets(buff, 256, file))
{
if(i++ != line)
fputs(buff, temp);
}
fclose(file);
fclose(temp);
remove(filename);
rename("temp.txt", filename);
}
int main()
{
int pil;
printf("1) - append\n");
printf("2) - update\n");
printf("3) - delete\n");
scanf("%d", &pil);
switch(pil)
{
case 1:
{
int count;
printf("number of records you want to append: ");
scanf("%d", &count);
struct hardware *hw = get_hardware_array(count);
update_hardware("hardware.txt" , hw, count);
break;
}
case 2:
{
int line;
printf("line you want to change: ");
scanf("%d", &line);
struct hardware hw = get_hardware(0);
change_line("hardware.txt", hw, line);
break;
}
case 3:
{
int line;
printf("line you want to delete: ");
scanf("%d", &line);
remove_line("hardware.txt", line);
break;
}
}
return 0;
}