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.
Related
I have a C++ program that takes a directory, like "D:\P4Test", and attempts to tell me how many bytes are in each subfolder and file within that directory. The code I currently have looks like this:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdint>
#include <sstream>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
using namespace std::filesystem;
int main()
{
string path = "D:\\P4Test";
for (const auto& entry : directory_iterator(path)) {
cout << entry.path() << std::endl;
uintmax_t fsize = file_size(entry.path());
cout << " ||| " << fsize << endl;
}
}
Yes, it has a lot of unnecessary includes and such, but that's for future things.
When I run this code, I don't get what I want. Here's a picture of what's in that directory, and the output.
As you can see, the output looks good, but it does not give me the bytes for what's in the folders called "Two" & "Three".
Both folders have a text file in them that's 5 bytes, but they report back 0.
Can anyone help me figure out why, and show me how to make the folders show their bytes, or direct me to where I can figure this out?
It looks like you are trying to do a recursive file size check, but you do not actually recurse into the directories. 1 way to do this is to stasrt with a function gets all of the file sizes:
void folder_size(std::filesystem::path path) {
for (const auto& entry : directory_iterator(path)) {
cout << entry.path() << std::endl;
uintmax_t fsize = file_size(entry.path());
cout << " ||| " << fsize << endl;
}
}
Now we simply a special case to deal with if the file type is a directory, we can do this with std::filesystem::directory_entry::is_directory:
if (entry.is_directory()) {
// Handle the directory
}
So how do we handle the directory, well we have a function that we made that takes a directory path and goes through it. Lets call that:
if (std::filesystem::is_directory(entry.path())) {
folder_size(entry.path())
}
Putting it all together:
void folder_size(std::filesystem::path path) {
for (const auto& entry : directory_iterator(path)) {
cout << entry.path() << std::endl;
uintmax_t fsize = file_size(entry.path());
cout << " ||| " << fsize << endl;
if (std::filesystem::is_directory(entry.path())) {
folder_size(entry.path())
}
}
}
NOTE: All of the above is example code. No compilation check has been conducted.
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";
}
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.
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
For some reason, I can't write anything to a .PGM file. The following code compiles without errors but nothing is written to the .PGM file it creates. I'm fairly new to C++ and pretty unfamiliar with working with strings in this syntax.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <sstream>
int main(){
// Initialize variables.
const int ncols = 30;
const int nrows = 20;
const int maxval = 255;
std::string filename;
// Prompt user for filename.
std::cout << "What would you like to name the file of the PGM image? Please include .PGM at the end of your name." << std::endl;
// Uses getline() function to retrieve input from user into a string.
std::getline(std::cin, filename);
// Creates output stream object to use with managing the file.
std::ofstream fileOut(filename.c_str(),std::ios_base::out
|std::ios_base::binary
|std::ios_base::trunc
);
fileOut.open(filename.c_str());
fileOut << "P2" << " " << ncols << " " << nrows << " " << maxval << "\n";
fileOut.close();
}
I know there is another SO question similar to this one, but I used that answer to get here. I can't even get it to write the header part and that's not even the point of the assignment. Can anyone help?