How to write and then read structure from file?

Hey guys, I have a structure like this, but I cant find out how to write this structure record to file, and then read it from that file? Can you help me out? :/ There will be alot of records, and i want to keep them at the file, and i will be filling him many times. So how to avoid rewrite? :/

struct azi
{
string to; // string
string ho; //string
string mo; //string
double no; //date
};

I want to enter information from the command line
Last edited on
Lets start with http://www.cplusplus.com/doc/tutorial/files/
You can avoid rewrite by either writing to another file, or appending to the end of a file.
Yes, but how to make a new name for new records everytime, when i shutdown and start the program again? :/
You can append the time to the end of the file name, or you can check if the file already exists and increment a counter that is appended to the end of the file name.

The first would be faster if you had a lot of files. you can use the #include <chrono>
http://www.cplusplus.com/reference/chrono/time_point/time_since_epoch/
may be a helpful page.
Okey guys, I've created something, but why my program doesnt create a new file with my information?? There is no errors in program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
        if(pas == 1)
        {
            cout << "Enter your record" ;
            cout << "Autorius: ";
            getline(cin, j.autorius);
            cout << "Pavadinimas: ";
            getline(cin, j.pavadinimas);
            cout << "Mokslo sritis: ";
            getline(cin, j.mokslosritis);
            cout << "Tyrimo Data: ";
            cin >> j.tyrimodata;
            ofstream myfile ("pvz.txt");
            if (myfile.is_open()){
                
                myfile << j.autorius;
                myfile << j.pavadinimas;
                myfile << j.mokslosritis;
                myfile << j.tyrimodata;
                myfile.close();
                
            }
                 }


ps. its only part of prpogram
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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
	std::string a,b,c,d;
	cout << "Enter your record" ;
	cout << "Autorius: ";
	getline(cin, a);
	cout << "Pavadinimas: ";
	getline(cin, b);
	cout << "Mokslo sritis: ";
	getline(cin, c);
	cout << "Tyrimo Data: ";
	cin >> d;
	ofstream myfile ("pvz.txt");
	if (myfile.is_open()){

		myfile << a;
		myfile << b;
		myfile << c;
		myfile << d;
		myfile.close();
	} else {
		cout << "error opening file pvz.txt" << endl;
	}
	
}


This code works for me. You could try manually setting the mode flags for opening the file.
Last edited on
Topic archived. No new replies allowed.