Doing arithmetic in file I/O

I'm not sure if this is possible but would like to ask if there's any way I could perform arithmetic on a file which I've created using file I/O.

For example,
I first input a number 5.
Then the next time I open my program and input 6, it will automatically add it up
and show me 11 on my .txt file.

Any hints to how I can make this happen? and how can I read the file from the program without going to my own .txt file?
Well, there are two main ways:
1. The C way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <cstdio>

int main()
{
    FILE * filehandle = fopen("file.txt","r");
    int ValueWrittenOnFile = 0;
    if(filehandle) // If file exists, read the value
    {
        fscanf(filehandle,"%d",&ValueWrittenOnFile);
        fclose(filehandle);
    }
    int UserInputValue = 0;
    scanf("%d",&UserInputValue);
    ValueWrittenOnFile += UserInputValue;
    filehandle = fopen("file.txt","w");
    if(!filehandle)
        return 1; // Error: No access to file.txt
    fprintf(filehandle,"%d",ValueWrittenOnFile);
    fclose(filehandle);
    return 0; // Success
}


(Caution: Has minimal error checking)
or:
2. The C++ way
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
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream file_output;
    ifstream file_input;
    int FileValue = 0;
    int UserValue = 0;
    file_input.open("file.txt");
    if(file_input.is_open())
    {
        file_input >> FileValue;
        file_input.close();
    }
    file_output.open("file.txt");
    cin >> UserValue;
    FileValue += UserValue;
    if(file_output.is_open())
    {
        file_output << FileValue;
        file_output.close();
    }
    return 0;
}

(Again, caution, minimal error checking)
Hey, thanks a lot! (:
Topic archived. No new replies allowed.