Sequential file access

So i'm trying to create a program that will read a file "Workers.txt" and read the numbers from it then write 3 additional employee idnumbers, hourly rate, and hours worked to the file. This is what I got so far and I can't seem to get it to work. Any help?

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
// Lab1203.cpp – Write data for 3 additional employees idnumber, hours worked, and
// hourly rate to workers.txt file
// Created by Taft Sanders on 10/31/12

#include <iostream>
#include <fstream>

using namespace std;

int main( )
{
int idNumber = 0;
double rate = 0.0;
double hours = 0.0;

ifstream workers;
workers.open("workers.txt", ios::in);

if(workers.is_open())
{
	for(int count=0; count<5;count++)
	{
	 workers>> idNumber>>rate>>hours;
	}
workers.close();
}

else
{
cout<< "The file could not be opened." << endl;
}


workers.open("workers.txt",ios::out);

if(workers.is_open())
{
    for(int count=4;count<8;count++)
    {
        cout<<"Enter ID Number: ";
        cin>>idNumber;
        cout<<"Enter rate: ";
        cin>>rate;
        cout<<"Enter hours: ";
        cin>>hours;

        workers<<idNumber<<""<<rate<<""<<hours<<""<<endl;
    }

    workers.close();
}

else
{
    cout << "The file could not be changed."<<endl;
}

system("pause");
return 0;
}
You have to create ofstream object to write into a file.
say ofstream out.(you cannot use same ifstream object "workers" for writing also) and write to the file.

File name can be same but ifstream and ofstream objects name should be different.
1
2
ifstream workers("workers.txt");
ofstream edited_workers("sales.txt");


To add to/edit an existing file, one way I knew is you can read the input file data and store it some where and write it again to the same file along with the other details.

Topic archived. No new replies allowed.