简体   繁体   中英

read/write struct from text file in c++

I have been stuck in the same place with this code for a while. And finally decided to ask it online. Any help would be appreciated.

I have created a struct and I'm able to add data to the struct but still not sure whether I'm following the correct methodology. The main problem lies when I try to read the data from the text file.

I seem to be getting an error saying :

error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::ifstream' (or there is no acceptable conversion)

The Struct:

struct bankDetails              //structure for bank details
{
    int acc_number;
    double acc_balance;
    double deposit_amt;
    double withdraw_amt;
    double interest_rate;
    //char acc_type;


};


struct CustDetails                     //structure for account details
{
    string cust_name;
    string cust_pass;
    bankDetails bankAccounts[99];
};

This is the code I wrote to read from the file.

CustDetails loadDataFromFile ()
{
    CustDetails x;
    ifstream  dimensionsInfile; 
    dimensionsInfile.open ("storage.txt");
    for (int i=0; i < 2; i++)                                                               
    {   // write struct data from file  
        dimensionsInfile>>
        &x.bankAccounts[i].acc_balance>>
        &x.bankAccounts[i].acc_number>>
        &x.cust_nam>>
        &x.cust_pass>>
        &x.bankAccounts[i].withdraw_amt>>
        &x.bankAccounts[i].deposit_amt>>
        &x.bankAccounts[i].interest_rate>>
        cout<<"Data loaded"<<endl;
    } 
    return x;

}

The code to write into the file:

void details_save(int num,CustDetails x)
{

    string  filePath = "storage.txt";                                                                               
    ofstream  dimensionsOutfile;                                                                    

    dimensionsOutfile.open ("storage.txt");                                             
    if (!dimensionsOutfile)
        {
            cout<<"Cannot load file"<<endl;
            return ;
        }
    else
        {
            for (int i=0; i < num; i++)                                                             
                {   // write struct data from file  
                    dimensionsOutfile<<
                    &x.bankAccounts[i].acc_balance<<
                    &x.bankAccounts[i].acc_number<<
                    &x.cust_name<<
                    &x.cust_pass<<
                    &x.bankAccounts[i].withdraw_amt<<
                    &x.bankAccounts[i].deposit_amt<<
                    &x.bankAccounts[i].interest_rate<<
                    cout<<" Customer 1 stored"<<endl;
                }
            cout <<"All details have been successfully saved"<<endl;
            dimensionsOutfile.close();
        }

}

Part of the main function:

#include "stdafx.h"
#include <string>
#include <string.h>
#include <ctime>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>

int main()

{
    int maxNum;
    CustDetails c;
    c = loadDataFromFile(); //loads data from the file

    {
            //This part adds and changes values
    }

    details_save(maxNum, c); //saves data back to the file
        return 0;
}

I'm a beginner in C++ any help would be much appreciated. Cheers!!

Read about file formats . You may need to specify yours (on paper....), then you could use some EBNF notation for that specification.

Your current code is probably misusing the operator >> and the operator << . You don't want to write pointers on file (even if you technically could), because reading them again is meaningless (because of ASLR , and because addresses are not guaranteed to stay the same from one run to the next, or from one executable to your program slightly improved tomorrow).

You might want to do some binary IO (but I don't recommend doing this). Then you would use some binary input function like std::istream::read to read a record (eg some POD struct ). But you cannot (meaningfully) do binary IO on complex classes, such as your CustDetails , containing non-POD data such as std::string -s.

Actually, data is often more important than the software reading and writing it. So it makes sense to have some more flexible data format (eg you want to be able, in two years, to have an improved version of your code read some data written by some old version of your code).

Hence, it is often preferable to use some textual format (and you need to define and document it). You could choose some existing ones, such as JSON , YAML , XML , S-expressions . You'll find many libraries to help you (eg jsoncpp for JSON etc etc...). Or you could also use your own parsing techniques.

You could also consider some database , perhaps as simple as sqlite .

Read also about serialization , application checkpointing , persistence , and portability .

In loadDataFromFile() just before

cout<<"";

replace the '>>' with ';'.

We cannot use >> operator with cout.

Although there is a better and easier way to do what you are doing. fstream.h has functions to directly write and read objects of classes or structures.

Here's the syntax:

<stream name>.read((char*)<object name>,sizeof(<struct/class name>));

So your loadDataFromFile can be simplified as:

CustDetails loadDataFromFile ()
{
CustDetails x;
ifstream  dimensionsInfile; 
dimensionsInfile.open ("storage.txt");                                                              
     // write struct data from file  
     dimensionsInfile.read((char*) CustDetails, sizeof(x));   
     cout<<"Data loaded"<<endl;
     return x;
}

Similarly write definition of Write function. It will save you a lot of time and trouble.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM