I have an assignment to take an input from the user and wrote it in file and successfully wrote the file like the function given below,and it is working nicely
void add_category(string NAME, int ID_category)
{
category* newnode;
newnode = new category;
newnode->name_of_category = NAME;
newnode->id = ID_category;
if (headd == NULL) {
headd = newnode;
newnode->next = NULL;
newnode->pre = NULL;
lastd = newnode;
}
else {
lastd->next = newnode;
newnode->pre = lastd;
newnode->next = NULL;
lastd = newnode;
}
dlength++;
ofstream file("Category.txt", ios::app);
category* temp = headd;
category* temp2;
while (temp != NULL) {
file << temp->name_of_category << endl;
file << temp->id << endl;
temp2 = temp;
temp = temp->next;
delete temp2;
}
file.close();
}
But the problem is that while opening a file by code get crashed or TBH I don't how I can open a file. I am using double linked list. My task is to open a file in a read mode and delete the category entered by the user. Here is my function of deleting the category:
void delete_category(string remove_name)
{
category* currentptr = headd;
category* temp;
category* temp2;
category* temp3 = headd;
ifstream file("Category.txt");
if (!file) {
cout << "file can not open" << endl;
}
else {
while (temp3 != NULL && !file.eof()) {
file >> temp3->name_of_category;
file >> temp3->id;
temp3 = temp3->next;
}
}
int save = search_category(remove_name);
cout << save << endl;
if (dlength <= 0) {
cout << " NO category found" << endl;
}
else {
if (save == 0) {
temp = headd;
headd = headd->next;
headd->pre = NULL;
}
else {
for (int i = 1; i < save; i++) {
currentptr = currentptr->next;
}
temp = currentptr->next;
temp2 = temp->next;
currentptr->next = temp2;
temp2->pre = currentptr;
}
dlength--;
delete temp;
cout << " Successfully Deleted the Category" << endl;
}
}
As I have called the searched function in the deleting category, I have used the same method for opening a file in search function:
int search_category(string search)
{
category* currentptr = headd;
int flag = 0;
category* temp3 = headd;
ifstream file("Category.txt");
if (!file) {
cout << "file can not open" << endl;
}
else {
while (temp3 != NULL && !file.eof()) {
file >> temp3->name_of_category;
file >> temp3->id;
temp3 = temp3->next;
}
}
for (int i = 0; i < dlength; i++) {
if (currentptr->name_of_category == search) {
flag = 1;
return i;
}
currentptr = currentptr->next;
}
if (flag == 0) {
cout << " Sorry not found" << endl;
return -1;
}
}
Please correct me where I am making a mistake to open a file.