bit-question
bit-question

Reputation: 3843

load multi-dimensional array into a data file in C++

In C++, how to implement the following functionality? Thanks. Assume in a program, I can get a matrix A = [1,2;2,1]. How to save it in an independent data file, e.g., data1.

Secondly, how to load this file data1 into my another program 2 as a matrix A.

Upvotes: 0

Views: 630

Answers (1)

BЈовић
BЈовић

Reputation: 64223

Struct for C++ File I/O binary file sample

       struct WebSites
       {
             char SiteName[100];
             int Rank;
       };

to write

     void write_to_binary_file(WebSites p_Data)
     {
          fstream binary_file("test.dat",ios::out|ios::binary|ios::app);
          binary_file.write(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
     }

Sample for C++ File I/O binary file read

 void read_from_binary_file()
 {
     WebSites p_Data;
     fstream binary_file("test.dat",ios::binary|ios::in);
     binary_file.read(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
     binary_file.close();

     cout<<p_Data.SiteName<<endl;
     cout<<"Rank :"<< p_Data.Rank<<endl;
 }

Upvotes: 1

Related Questions