Text file using filehandling

Jan 6, 2015 at 7:02am

For Example
i have made a text file included some students data.
Now i want to change just a single student data. That file should remain same just that student's data replace.
Any logic...
Jan 6, 2015 at 9:32am
yup, open an ifstream, read the file, change what you want to change, open an ofstream, write it back out. At least that's the method I know...
Jan 6, 2015 at 11:26am
But when we use this method whole text file will change with new data #bugbyte
But i want to change the data of specific student while other students's data must remain same.
Hope so Now you got my point.
Jan 6, 2015 at 12:08pm
Indeed I got your point. Maybe if you would show some code, we could tell you why it doesn't work the way you want to. #beingProactive
here is a mini example (I will stop doing these soon):

data.txt:

Foo 9
Bar 0
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
// format: <name> <number>
// increment number if name is "Bar"
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

int main()
{
    using namespace std;
    const string filename = "data.txt";
    ifstream file(filename);
    if (!file) {
        cout << "Could not open file '" << filename << "'\n";
        return 1;
    }

    vector<string> content;
    string name;
    int num;
    while (file >> name >> num) {
        if (name == "Bar") ++num;
        content.push_back(name + ' ' + to_string(num));
    }

    ofstream out(filename);
    for (const auto& line : content)
        out << line << '\n';
    return 0;
}
Last edited on Jan 6, 2015 at 12:09pm
Topic archived. No new replies allowed.