C++ program to load the content of a class of another file - c++

I have a c++ program like this:
#include<iostream>
using namespace std;
class A
{
public:
void display();
};
void A::display() {
cout<<"This is from first program";
}
int main()
{
A a1;
a1.display();
return 0;
}
I want to save a1 into a file and call the display function by using this object from another c++ program. Is it possible? Is it possible to have main() function in both c++ programs? I am very new in C++. Please help me.

Given your comments, I believe that you're looking for std::ofstream in your first program and std::ifstream in your second program. If program A is your first program with a very large code base and program B is your second program which will want to display the data from program A, then program A would use std::ofstream and program B would use std::ifstream.
cppreference - ofstream
cppreference - ifstream
If you follow the links, you'll find the description of what they do and at the bottom of the page, there's a code example. Don't start with program A that takes 7-8 hours to compute. You'll have to make sure that the output is correct before you can even use the data for input and any mistake on the way means that you'll have to restart. If you want to test and manually verify your data you can skip the second parameter as such, std::ofstream ostrm(filename) but then you need to rework how you operate the stream. Depending on your data, this will be the critical part of the operation.
// Code example from cppreference - ofstream
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string filename = "Test.b";
{
// This will create a file, Test.b, and open an output stream to it.
std::ofstream ostrm(filename, std::ios::binary);
// Depending on your data, this is where you'll modify the code
double d = 3.14;
ostrm.write(reinterpret_cast<char*>(&d), sizeof d); // binary output
ostrm << 123 << "abc" << '\n'; // text output
}
// Input stream which will read back the data written to Test.b
std::ifstream istrm(filename, std::ios::binary);
double d;
istrm.read(reinterpret_cast<char*>(&d), sizeof d);
int n;
std::string s;
istrm >> n >> s;
std::cout << " read back: " << d << " " << n << " " << s << '\n';
}
With your data correctly outputted to a file you'll be able to read from it by creating the std::ifstream. Make sure to verify that the stream is open:
std::ifstream istrm(filename, std::ios::binary);
if(istrm.is_open())
{
//Process data
}

This will be your File.h
#ifndef FILE_H
#define FILE_H
class A
{
public:
void display();
};
#endif
This will be your File.cpp
#include <iostream>
#include "File.h"
void A::display() {
std::cout<<"This is from first program";
}
This will be you main.cpp
#include <iostream>
#include "File.h"
int main()
{
A a1;
a1.display();
return 0;
}
You compile this with g++ File.cpp main.cpp

Related

Pass a pointer to a file buffer to a class, expecting to read from file inside a class

I want to learn how to search in the file by passing the pointer of the stream to a class.
I can successfully get the first character from the file using std::fstream and std::filebuf*
char symbol;
std::fstream by_fstream;
by_fstream.open("First_test_input.txt");
std::filebuf* input_buffer = by_fstream.rdbuf();
symbol = input_buffer -> sbumpc();
std::cout << "\nSymbol that get from a file by rdbuf(): " << symbol;
Output: Symbol that get from a file by rdbuf(): M
But I'm not sure how can I send any pointer to my original stream of the file from main to a class.
Ideally, it would be great to do something like this:
#include <iostream>
#include <fstream>
class from_file
{
public:
char c;
from_file () {
std::cout << "\nCharacter that get from file by to class variable"
<<" then printed: " << c;
};
from_file (char *pointer){
c = pointer -> sbumpc();
};
~from_file ();
};
int main(){
std::fstream by_fstream;
by_fstream.open("First_test_input.txt");
std::filebuf* input_buffer = by_fstream.rdbuf();
from_file send(&input_buffer);
from_file show;
return 0;
}
Looking for advice on where I can find documentation about similar headers to do a such task.
You are going about this all wrong.
First off, you should pass around (a reference to) the stream itself, not its internal buffer. Use std::istream methods like read() or get() or operator>> to read from the stream, let it handle it own buffer for you.
Secondly, you are trying to make a 2nd completely separate object "magically" know what a previous object is holding. That is not going to work out the way you want, either.
Try something more like this instead:
#include <iostream>
#include <fstream>
class from_stream
{
public:
char c;
from_stream (std::istream &in){
c = in.get();
// or: in.get(c);
// or: in.read(&c, 1);
// or: in >> c;
};
void show() const {
std::cout << "\nCharacter that get from file by to class variable"
<<" then printed: " << c;
}
};
int main(){
std::ifstream by_ifstream;
by_ifstream.open("First_test_input.txt");
from_stream send(by_ifstream);
send.show();
return 0;
}

how exactly input and output file streams work in c++

I came across the following observation while working with input and output file streams and I am confused. Can anyone tell me why this happens:
I saved a txt file on my desktop by the name hello which contains the following text:
Hello my name is xyz
Next, I ran the following code:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream strm;
strm.open("C:\\Users\\SWARAJ SONAVANE\\Desktop\\hello.txt");
if (strm.fail())
{
std::cout << "failed.... :(\n";
}
//std::string p;
//strm >> p;
//std::cout << p;
strm << "random text";
}
The content of the hello.txt file after running this code was:
random textme is xyz
Now i ran the following code on the original hello.txt file
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream strm;
strm.open("C:\\Users\\SWARAJ SONAVANE\\Desktop\\hello.txt");
if (strm.fail())
{
std::cout << "failed.... :(\n";
}
std::string p;
strm >> p;
std::cout << p;
strm << "random text";
}
The console printed hello but the contents of the hello.txt file remained unaltered.
Can anybody explain, what difference did reading stream into the string make?
If you want to know how streams work in C++ then you need a reference work (and maybe a tutorial as well), obviously its much more complicated than can be explained here.
The reason for what you found is the rule that if you switch from reading to writing (or vice versa) you must execute a positioning or flushing operation before you make the switch. Try the following code instead
int main()
{
std::fstream strm;
strm.open("C:\\Users\\SWARAJ SONAVANE\\Desktop\\hello.txt");
if (strm.fail())
{
std::cout << "failed.... :(\n";
}
std::string p;
strm >> p;
std::cout << p;
strm.seekp(0); // position the stream at the beginning
strm << "random text";
}

C++ cereal de-serialization trouble with large size vector

I hope to serialize large size vector with cereal, C++ serialization library.
But, if trying to do that, the exception "Failed to read " + std::to_string(size) + " bytes from input stream! Read " + std::to_string(readSize)" is thrown.
Does anyone know a good solution for this?
I'm using VisualStudio 2017.
The source code is shown below.
#include <iostream>
#include <fstream>
#include "include\cereal\cereal.hpp"
#include "include\cereal\archives\binary.hpp"
#include "include\cereal\types\vector.hpp"
#include "include\cereal\types\string.hpp"
void show(std::vector<int> v) {
for (auto i : v)std::cout << i << ",";
std::cout << std::endl;
}
int main(void) {
const std::string file_name = "out.cereal";
{
std::vector<int> src;
// const int STOP = 10; //OK
const int STOP = 1000; // NG
for (int i = 0; i < STOP; i++)src.push_back(i);
std::cout << "src:" << std::endl;
show(src);
std::ofstream ofs(file_name, std::ios::binary);
cereal::BinaryOutputArchive archive(ofs);
archive(src);
}
{
std::vector<int> dst;
std::fstream fs(file_name);
cereal::BinaryInputArchive iarchive(fs);
iarchive(dst);
std::cout << "dst:" << std::endl;
show(dst);
}
#ifdef _MSC_VER
system("pause");
#endif
return 0;
}
You code works fine for me in Linux, so I think it is to do with the difference between text and binary handling on Windows. Check that you pass std::ios::binary when you are constructing the input stream. Also construct it as std::ifstream rather than just std::fstream.
I think this might have to do with Windows expecting (or adding) a Unicode byte-order mark, which is confusing the serializer.

Creating and copying text to multiple .cpp files in C++

So I'm doing the Euler Projects and I'm storing all my Solutions in one Program. I have just started on C++, so I don't know if this is a good way to do it. Anyway, each .cpp file contains one Problem. So basically my structure is like this:
"Executer.cpp"
include <iostream>
include "other.h"
int main() {
Problem1();
Problem2();
// etc.
system("pause")
return 0;
}
"Other.h"
void Problem1();
void Problem2();
// etc.
"Problem_X.cpp" (X denotes the number of the task). I have a lot of these files.
/* PROBLEM X
*/
#include <iostream>
#include <fstream>
#include <time.h>
void ProblemX() {
time_t t1, t2;
t1 = clock();
// Code goes here
t2 = clock();
float diff((float)t2 - (float)t1);
float seconds = diff / CLOCKS_PER_SEC;
// Results
std::ofstream myFile("result.txt");
//myFile << sum;
myFile.close();
std::cout << "-------------------- Problem X -------------------" << std::endl;
std::cout << "I ran for: " << seconds << " seconds" << std::endl << std::endl;
}
Now, the Projects consist of almost 600 Problems, which means I have to create 600 files and copy the template to each of those documents. So I thought I could just make a program for doing it.
Basically, I put "Problem_X.cpp" into a text file called "standard.txt". I then wrote the following program, which i run from my int main by including the function declaration in "other.h" and calling the function from "Executer.cpp". It runs fine when copying text from one text-file to another text-file. But now (I assume since I'm trying to copy into a .cpp file) nothing happens:
#include <fstream>
#include <iostream>
#include <sstream>
void CreateNewFile(int number) // denotes the number of the problem you wish to create
{
std::string strNumber = static_cast<std::ostringstream*>(&(std::ostringstream() << Number))->str();
std::string str1 = "Problem_";
std::string str2 = ".cpp";
std::string strr;
strr.append(str1); strr.append(strNumber); strr.append(str2);
std::ofstream out(strr); //this creates it.
std::ifstream in("standard.txt");
if (!out.is_open())
{
std::cout << "ERROR: Can not open document2.txt" << std::endl;
return;
}
std::string str;
while (std::getline(in, str)) {
out << str << std::endl;
}
in.close();
out.close();
}
Does anyone have experience doing something like this? I can't find any posts on google and I am out of ideas about where to look.
The program actually runs as is is intended. It creates the new "Problem_X.cpp" files just right. They are just not imported in the VS source folder. If anyone has a quick solution for this, they are welcome to leave it in a comment here.

create multiple text files inside a loop

I want to create some text file in C++. For example: I will run a loop from 1 to 5 and create the following files:
1.txt
2.txt
3.txt
4.txt
5.txt
is it possible? I have made a sample code:
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
main()
{
FILE *fp;
int i;
for(i=1;i<=5;i++)
{
//fp=fopen("%d.txt","r",i); //what will go here??
}
}
I am confused about what I will write inside the loop. how can I create those files?
char i;
char fileName[] = "0.txt";
for(i='1';i<='5';i++)
{
fileName[0]=i;
fp=fopen(fileName,"r"); //what will go here??
//...
}
You can use sprintf if this is too simple for your case;
Since you tag c++, I think fstream string is the thing to use.
A simple c++ example
#include <fstream>
#include <string>
using namespace std;
int main(){
string base(".txt");
for(int i=1;i<=5;++i){
ofstream(to_string(i)+base);// to_string() need c++11
}
}
If you still don't have to_string (you don't have c++11 or your compiler just don't have this) you can use this simple version for now. (better put this in your own namespace)
#include <string>
#include <sstream>
std::string to_string(int i){
std::stringstream s;
s << i;
return s.str();
}
You can use a std::stringstream to compose the file name before passing it to the std::ofstream constructor as a std::string.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
int main()
{
std::cout << "How many files do you want to create? ";
int n;
std::cin >> n;
std::cout << "How many digits do you want to display? ";
int n_digits;
std::cin >> n_digits; // i.e. zeroes == 3 -> 001.txt
std::cout << "Enter a common prefix for all the files: ";
std::string prefix;
std::cin.ignore();
std::getline(std::cin, prefix); // i.e. prefix == "file" -> file001.txt
std::string ext(".txt");
for ( int i = 1; i <= n; ++i )
{ // use a stringstream to create a file names like: prefix001.txt
std::stringstream ss;
ss << prefix << std::setfill('0') << std::setw(n_digits) << i << ext;
// open the file. If not c++11 use ss.str().c_str() instead
std::ofstream file( ss.str() );
if ( !file )
{
std::cerr << "Error: failed to create file " << ss.str() << '\n';
break;
}
// write something to the newly created file
file << "This is file: " << ss.str() << "\n\nHello!\n";
if ( !file )
{
std::cerr << "Error: failed to write to file " << ss.str() << '\n';
break;
}
}
}
#include <iostream>
#include <fstream>
int main(void)
{
std::ofstream out; // you must call out.close() inside loop to be able to open another file for writting otherwise you'll get only the first one "a.txt"
std::string sFileName;
for(char c('a'); c < 'f'; c++)
{
sFileName = c;
sFileName += ".txt";
out.open(sFileName.c_str(), std::ios::out);
// std::ofstream out(sFileName.c_str(), std::ios::out); // here you are not obliged to call out.close() because the first out is not the very second and so on...
out.close(); // very important if you use the same ofstream to open another file
}
std::cout << std::endl;
return 0;
}
*** to be able to use one ostream object in opening many files you must close the precedent file to be able to open the next otherwise it fails trying creating the next one.