Delete file contents

closed account (1vf9z8AR)
I wrote my program but delete is not working.I can't understand what is wrong.(line 85-109)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include<iostream>
#include<fstream>
using namespace std;
struct student
{
    char name[80];
    int rno;
};
int main()
{
        student s1;
    int option,n;
    char ch;
    do
    {
    cout<<"Enter 1 to write file\nEnter 2 to read file\n3 to search file\n4 to modify file\n5 to delete";cin>>option;
    if(option==1)
    {
    ofstream f1;
    f1.open("file.dat",ios::binary);
    cout<<"Enter number of customers";cin>>n;
    for(int i=0;i<n;i++)
    {
    cout<<"\nEnter name(dot to terminate)";cin.getline(s1.name,80,'.');
    cout<<"\nEnter roll number";cin>>s1.rno;
        f1.write((char*)&s1,sizeof(student));
    }
      f1.close();
    }

    else if(option==2)
    {
           ifstream r1;
           r1.open("file.dat",ios::binary) ;
                while(   r1.read((char*)&s1,sizeof(student)))
           {
           cout<<"Name"<<s1.name<<endl;
           cout<<"Roll number"<<s1.rno<<endl;
           }
           r1.close();
    }

    else if(option==3)
    {
        int rno;
        cout<<"Enter roll number to search for";cin>>rno;
       bool condition=false;
        ifstream a1;
        a1.open("file.dat",ios::binary);
        while( a1.read((char*)&s1,sizeof(student)))
    {
        if (rno==s1.rno)
                {
                    condition=true;
                    cout<<"Name:"<<s1.name<<endl;
                    cout<<"Roll number"<<s1.rno<<endl;
                };
    }
    if(condition==false)
    cout<<"Not found"<<endl;
    a1.close();
    }

    else if(option==4)
    {
        int r;
        fstream q1;
        q1.open("file.dat",ios::in|ios::out|ios::binary);
        cout<<"Enter roll number to modify";cin>>r;
        bool flag=false;
        while(q1.read((char* )&s1,sizeof(student)))
        {
            if(s1.rno==r)
            {
                flag=true;
                cout<<"\nEnter new name(dot to end input)";cin.getline(s1.name,80,'.');
                cout<<"\nEnter roll number";cin>>s1.rno;
q1.write((char*)&s1,sizeof(student));
            }
        }
        if(!flag)
            cout<<"\nNot found"<<endl;
        q1.close();
    }
    else if(option==5)
    {
        int rno;
              fstream w1;fstream e1;
              e1.open("temp.dat",ios::in|ios::out|ios::binary);
              w1.open("file.dat",ios::in|ios::out|ios::binary);
              cout<<"\nEnter roll number to delete";cin>>rno;
              bool value=false;
              while(w1.read((char*)&s1,sizeof(student)))
              {
                  if(s1.rno==rno)
                      value=true;
                  else
                         e1.write((char*)&s1,sizeof(student));
              }
                             if(value==false)
                cout<<"\nNot found"<<endl;
                else
                {
                     remove("file.dat");
              rename("temp.dat","file.dat");
                }
              e1.close();
              w1.close();
    }

    cout<<"Do you want to continue?(y/n)";cin>>ch;
    }while((ch=='y')||(ch=='Y'));
               return 0;
}


EDIT:
The delete coding magnified and changed.But whole file gets deleted now.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    else if(option==5)
    {
        int rno;
              fstream w1;fstream e1;
              e1.open("temp.dat",ios::in|ios::out|ios::binary);
              w1.open("file.dat",ios::in|ios::out|ios::binary);
              cout<<"\nEnter roll number to delete";cin>>rno;
              bool value=false;
              while(w1.read((char*)&s1,sizeof(student)))
              {
                  if(s1.rno==rno)
                      value=true;
                  else
                         e1.write((char*)&s1,sizeof(student));
              }
                                      e1.close();
              w1.close();
                             if(value==false)
                             {
                cout<<"\nNot found"<<endl;
                             }
                else
                {
                     remove("file.dat");
              rename("temp.dat","file.dat");
                }
    }
Last edited on
Close the files before remove(...)/rename(...). stream operations are buffered and might not be physically written.
closed account (1vf9z8AR)
Now the whole file gets deleted

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include<iostream>
#include<fstream>
using namespace std;
struct student
{
    char name[80];
    int rno;
};
int main()
{
        student s1;
    int option,n;
    char ch;
    do
    {
    cout<<"Enter 1 to write file\nEnter 2 to read file\n3 to search file\n4 to modify file\n5 to delete";cin>>option;
    if(option==1)
    {
    ofstream f1;
    f1.open("file.dat",ios::binary);
    cout<<"Enter number of customers";cin>>n;
    for(int i=0;i<n;i++)
    {
    cout<<"\nEnter name(dot to terminate)";cin.getline(s1.name,80,'.');
    cout<<"\nEnter roll number";cin>>s1.rno;
        f1.write((char*)&s1,sizeof(student));
    }
      f1.close();
    }

    else if(option==2)
    {
           ifstream r1;
           r1.open("file.dat",ios::binary) ;
                while(   r1.read((char*)&s1,sizeof(student)))
           {
           cout<<"Name"<<s1.name<<endl;
           cout<<"Roll number"<<s1.rno<<endl;
           }
           r1.close();
    }

    else if(option==3)
    {
        int rno;
        cout<<"Enter roll number to search for";cin>>rno;
       bool condition=false;
        ifstream a1;
        a1.open("file.dat",ios::binary);
        while( a1.read((char*)&s1,sizeof(student)))
    {
        if (rno==s1.rno)
                {
                    condition=true;
                    cout<<"Name:"<<s1.name<<endl;
                    cout<<"Roll number"<<s1.rno<<endl;
                };
    }
    if(condition==false)
    cout<<"Not found"<<endl;
    a1.close();
    }

    else if(option==4)
    {
        int r;
        fstream q1;
        q1.open("file.dat",ios::in|ios::out|ios::binary);
        cout<<"Enter roll number to modify";cin>>r;
        bool flag=false;
        while(q1.read((char* )&s1,sizeof(student)))
        {
            if(s1.rno==r)
            {
                flag=true;
                cout<<"\nEnter new name(dot to end input)";cin.getline(s1.name,80,'.');
                cout<<"\nEnter roll number";cin>>s1.rno;
q1.write((char*)&s1,sizeof(student));
            }
        }
        if(!flag)
            cout<<"\nNot found"<<endl;
        q1.close();
    }
    else if(option==5)
    {
        int rno;
              fstream w1;fstream e1;
              e1.open("temp.dat",ios::in|ios::out|ios::binary);
              w1.open("file.dat",ios::in|ios::out|ios::binary);
              cout<<"\nEnter roll number to delete";cin>>rno;
              bool value=false;
              while(w1.read((char*)&s1,sizeof(student)))
              {
                  if(s1.rno==rno)
                      value=true;
                  else
                         e1.write((char*)&s1,sizeof(student));
              }
                                      e1.close();
              w1.close();
                             if(value==false)
                             {
                cout<<"\nNot found"<<endl;
                             }
                else
                {
                     remove("file.dat");
              rename("temp.dat","file.dat");
                }
    }

    cout<<"Do you want to continue?(y/n)";cin>>ch;
    }while((ch=='y')||(ch=='Y'));
               return 0;
}
Last edited on
Hints:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#include <cstdio>
#include <fstream>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>

struct Student {
    std::string name;
    int rno {};
};

void displayMenu();
int askForInteger(int min, int max);
void writeToFile();
void readFromFile();
void searchRollNumberInFile();
void modifyFile();
void deleteFromFile();

int main()
{
    std::string line;
    do {
        displayMenu();
        int option = askForInteger(1, 5);
        switch(option) {
        case 1:
            writeToFile();
            break;
        case 2:
            readFromFile();
            break;
        case 3:
            searchRollNumberInFile();
            break;
        case 4:
            modifyFile();
            break;
        case 5:
            deleteFromFile();
            break;
        }
        std::cout << "Do you want to continue (y/n)? ";
        std::getline(std::cin, line);
    } while(line.at(0) == 'y' || line.at(0) == 'Y');
    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    return 0;
}

void displayMenu()
{
    std::cout << "1 - write to file\n2 - read from file\n3 - search in file\n"
                 "4 - modify file\n5 - delete from file\n";
}

int askForInteger(int min, int max)
{
    std::cout << "Please insert an integer (" << min << '-' << max << "): ";
    int answ {};
    for(std::string line; std::getline(std::cin, line); /**/) {
        try {
            answ = std::stoi(line); // may throw std::invalid_argument or
                                    // std::out_of_range
            if(answ < min || max < answ) { 
                throw std::out_of_range("User input out of range");
            }
            break; // no errors: exit for-loop
        // } catch(std::invalid_argument& e) {
            // //
        // } catch(std::out_of_range& e) {
            // //
        } catch(std::logic_error& e) {
            std::cout << "Please insert an integer (" << min << '-' << max 
                      << "): ";
        }
    }
    return answ;
}

void writeToFile()
{
    std::cout << "How many customers do you want to enter?\n";
    int n = askForInteger(1, std::numeric_limits<int>::max());
    std::ofstream f1("file.dat");
    for(int i=0; i<n; i++) {
        std::cout << "\nCustomer n. " << i+1 << ":\nname (max 80 characters)? ";
        std::string line;
        std::getline(std::cin, line);
        if(line.length() != 80) { line.resize(80, ' '); }
        std::cout << "roll number?\n";
        int rno = askForInteger(1, std::numeric_limits<int>::max());
        f1 << line << ' ' << rno << '\n';
    }
    f1.close();
}

void readFromFile()
{
    std::ifstream r1("file.dat");
    for(std::string line; std::getline(r1, line); /**/) {
        // The following lines are pointless: just to show how to create
        // a Student from the data inside the file:
        Student s;
        s.rno = std::stoi(line.substr(line.rfind(' ')));
        s.name = line.substr(0, line.find("  "));
        std::cout << "Name: " << s.name << "; roll number: " << s.rno << '\n';
    }
    r1.close();
}

void searchRollNumberInFile()
{
    std::cout << "Enter roll number to search for.\n";
    int rno = askForInteger(1, std::numeric_limits<int>::max());
    std::ifstream a1("file.dat");
    for(std::string line; std::getline(a1, line); /**/) {
        int rno_int = std::stoi(line.substr(line.rfind(' ')));
        if(rno == rno_int) {
            Student s;
            s.rno = rno_int;
            s.name = line.substr(0, line.find("  "));
            std::cout << "Name: " << s.name << "; roll number: " << s.rno << '\n';
            return;
        }
    }
    std::cout << "Not found.\n";
    a1.close();
}

void modifyFile()
{
    std::cout << "Enter roll number to modify.\n";
    int r = askForInteger(1, std::numeric_limits<int>::max());
    std::ifstream q1("file.dat");
    bool found { false };
    for(std::string line; std::getline(q1, line); /**/) {
        if(r == std::stoi(line.substr(line.rfind(' ')))) {
            found = true;
            break;
        }
    }
    q1.close();
    if(found) { // now we know for sure the searched rno exists.
        std::ifstream q1("file.dat");
        std::ofstream q2("tmp_file.dat");
        for(std::string line; std::getline(q1, line); /**/) {
            if(r == std::stoi(line.substr(line.rfind(' ')))) { // get new data
                std::cout << "Enter new name (max 80 characters): ";
                std::getline(std::cin, line);
                if(line.length() != 80) { line.resize(80, ' '); }
                std::cout <<"\nEnter new roll number.\n";
                int rno = askForInteger(1, std::numeric_limits<int>::max());
                line += ' ' + std::to_string(rno);
            }
            q2 << line << '\n';
        }
        q1.close();
        q2.close();
        std::remove("file.dat");
        std::rename("tmp_file.dat", "file.dat");
    } else {
        std::cout << " Not found.\n";
    }
}

void deleteFromFile()
{
    std::cout << "Enter roll number to modify.\n";
    int r = askForInteger(1, std::numeric_limits<int>::max());
    std::ifstream q1("file.dat");
    bool found { false };
    for(std::string line; std::getline(q1, line); /**/) {
        if(r == std::stoi(line.substr(line.rfind(' ')))) {
            found = true;
            break;
        }
    }
    q1.close();
    if(found) { // now we know for sure the searched rno exists.
        std::ifstream q1("file.dat");
        std::ofstream q2("tmp_file.dat");
        for(std::string line; std::getline(q1, line); /**/) {
            if(r != std::stoi(line.substr(line.rfind(' ')))) {
                q2 << line << '\n';
            }
        }
        q1.close();
        q2.close();
        std::remove("file.dat");
        std::rename("tmp_file.dat", "file.dat");
    } else {
        std::cout << " Not found.\n";
    }
}

Topic archived. No new replies allowed.