Here is my attempt
using namespace std;
int main()
{
mt19937 mt(time(0));
cout << mt() << endl;
cout << "----" << endl;
std::ofstream ofs;
ofs.open("/path/save", ios_base::app | ifstream::binary);
ofs << mt;
ofs.close();
cout << mt() << endl;
cout << "----" << endl;
std::ifstream ifs;
ifs.open("/path/save", ios::in | ifstream::binary);
ifs >> mt;
ifs.close();
cout << mt() << endl;
return 0;
}
Here is a possible output
1442642936
----
1503923883
----
3268552048
I expected the two last number to be the same. Obviously, I have failed to write and/or read my mt19937. Can you help fixing this code?
When you open your file for writing, you're appending to an existing file. When you read it back in, you read from the start.
Assuming you don't want to keep the existing content, change the open call to
ofs.open("/path/save", ios_base::trunc | ifstream::binary);
Using the trunc flag instead of app will truncate the existing file, so when you reopen it you're reading in the data you just wrote and not old data that was already there.
Related
I'm trying to make a hash program that makes hashes for you. I know it's been done before but I'm trying to recreate it. The problem I'm having is that I'm trying to add logs for each hash and output it to a "DataLog.txt" file. So far it's going Great! The only problem is that I'm trying to add a newline before each output to the text file. At the moment it writes it to the text file, then when it repeats to write again it just overlaps the previous writing. This is the code I have for the file outputting so far.
std::ofstream file;
file.open("DataLog (2).txt");
file << input << hash;
file.close();
The entire main function I have is also listed below. It might be a little long so get ready.
int main() {
while (1) {
std::cout << "Welcome to SHA256 Generator! Please enter the string you would like to convert to a hash:" << std::endl;
std::string input;
std::cin >> input;
std::cout << "Hash - " << sha256(input);
auto hash = ConvertToString(sha256(input));
std::ofstream file;
file.open("DataLog (2).txt");
file << input << hash;
file.close();
std::cout << std::endl;
std::cout << std::endl;
std::cout << "Would you like to convert another hash? Please enter either yes or no for your respose." << std::endl;
std::string response;
std::cin >> response;
if (response == "no")
return 0;
while (response != "yes" ) {
std::cout << std::endl;
std::cout << "Sorry I didn't get that. Can you try typing either yes or no again?" << std::endl;
std::string responseRepeat;
std::cin >> responseRepeat;
if (responseRepeat == "yes" || responseRepeat == "no") {
clear();
break;
}
}
clear();
}
return 0;
}
Ah I see, you want to add a line before each line. I think what you are looking for lies in file << input << hash;
So since file is your fstream output, you can treat it like cout. So the solution here would be file << input << hash << endl;
Now also make sure to open file in append mode by file.open(filename, ios::app); if you dont want your text to override.
I am trying to get the file size of a file with c++. The code is like this:
ifstream fin(filepth, ios::in | ios::binary | ios::ate);
if (!fin.is_open()) {
cout << "cannot open file:" << filepth << endl;
}
int len = fin.tellg();
fin.seekg(0, ios::beg);
fin.clear();
cout << "file length is: " << len << endl;
cout << "file length is: " << fs::file_size(fs::path(filepth)) << endl;
It turns out that the method of ios::ate got the wrong result. What did I miss and how could I got the correct result ?
I got the reason of the problem. My file is about 9 gigabytes long, which cannot be expressed by a 32 bit int variable. I used int64_t and the problem no longer exists.
Below is link for details as I think return type of file_size needs to typecast:
https://www.codingame.com/playgrounds/5659/c17-filesystem
I'm going through a text-book where an exercise entails copying text from one file and write it's lower-case equivalent to another file. I can't seem to find a way to do that using just I/O streams (most of the solutions I found online use stream buffers).
My code is this
int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';
cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};
fs << "LoRem ipSUM teXt TaXi";
char ch;
while (fsi.get(ch)) {
fs2 << ch;
}
After running nothing is written to the second file (f_name2). It's just a blank file.
Edit:
This doesn't work either
int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';
cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};
fs << "LoRem ipSUM teXt TaXi";
char ch;
while (fsi>>ch) {
fs2 << ch;
}
}
You are complicating your task for no apparent gain. There is no need for
ofstream fs{ f_name1 };
fs << "LoRem ipSUM teXt TaXi";
Use a text editor and create the contents of the input file outside the program.
Here's an updated version of your main fuction:
int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';
cin >> f_name1 >> f_name2;
ifstream fs1{f_name1};
if ( !fs1 )
{
std::cerr << "Unable to open " << f_name1 << " to read from.\n";
return EXIT_FAILURE;
}
ofstream fs2{f_name2};
if ( !fs2 )
{
std::cerr << "Unable to open " << f_name2 << " to write to.\n";
return EXIT_FAILURE;
}
// Using ostream::put() seems the right function to use
// for writing when you are using istream::getc() for reading.
char ch;
while (fs1.get(ch))
{
fs2.put(std::tolower(ch));
}
}
Hmm. So you're writing to the file and then reading the contents and writing out again. Okay...
You might need to fs.flush() after the fs << code. The data can be buffered, waiting for a newline character to trigger a flush, or doing one yourself.
I'd also put in some print statements in your while loop to make sure you're getting what you think you're getting.
I'm quite new to C++ programming, and I'm having trouble reading from an already open file. What I'm doing is writing to a file, reading from it, adding to the end of it, and then trying to read from it again without having to close the original ifstream. The code is as follows:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream myFile ("example.dat");
// Open and write to file
if (myFile.is_open())
{
myFile << "This is a line." << endl;
myFile << "This is another line." << endl;
myFile.close();
}
else cout << "no";
// Open and read from file
string line;
ifstream myFilein ("example.dat");
if (myFilein.is_open())
{
while (getline(myFilein,line))
{
cout << line << myFilein.tellg() << endl;
}
//myFilein.close();
}
// Open and add to end of file
if (!myFile.is_open())
{
myFile.open("example.dat", ios::app);
myFile << "This is the last line." << endl;
myFile.close();
}
//myFilein.open("example.dat", ios::ate);
// Read from already open file
myFilein.seekg(0, ios::beg);
if (myFilein.is_open())
{
cout << "myFilein is open. " << myFilein.tellg() << endl;
while (!myFilein.eof())
{
getline(myFilein, line);
cout << line << endl;
}
}
myFilein.close();
int holdClose;
cin >> holdClose;
return 0;
}
Obviously, something is going wrong, as tellg() is returning a value of -1 after the initial read (i.e., after it hits the end of the file), but I'm not entirely sure why it's returning -1, since I'm trying to reset the position to the beginning of the file. Is there something I'm missing or misunderstanding about how this works? If I close and re-open the file, then it's fine, but I'm curious if there's a way to keep reading from it without having to close it, if that makes sense. Thank you for your help :)
You didn't clear the state of the stream, thus the seekg call did nothing. You need to add myFilein.clear() before the repositioning.
Can someone with a little time on their hands please compile and run this code and see where I am going wrong?
#include <iostream>
#include <fstream>
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::ios;
int main()
{
int numbers = 0;
//create and open file
ifstream inFile;
ofstream outFile;
inFile.open ("numbers.txt", ios::in);
outFile.open ("evenNumbers.txt", ios::out);
//determine whether the file was opened
if (inFile.is_open() && outFile.is_open())
{
//read numbers file
inFile >> numbers;
while (!inFile.eof())
{
//look for even numbers
if (numbers %2 == 0)
{
outFile << numbers << endl;
//cout << numbers << endl;
}
inFile >> numbers;
}
//end while
//close files
outFile.close();
inFile.close();
cout << "Program successful. File complete." << endl;
}
//if file fails to open, display error message
else
cout << " File could not be opened " << endl;
//end if
system ("pause");
return 0;
} //end of main function
Your code has quite a few problems:
ifstream inFile;
inFile.open("numbers.txt", ios::in);
It's not exactly an error, but ios::in is the default for an ifstream, and you typically supply the file name to the constructor, something like this:
ifstream inFile("numbers.txt");
Then we have this:
getline(inFile, name);
inFile >> num;
while (inFile.eof())
while (inFile.eof()) seems to have the logic backwards -- you want to read until you reach the end of the, then quit. The rest of your loop will work (unusual for one that uses file.eof() as the condition) but is unnecessarily long and difficult to read.
//create file object and open the file
ofstream outFile;
outFile.open("updatedNumbers.txt", ios::out);
As you'd expect from the previous comment, ios::out is the default for an ofstream, and you usually give the file name to the constructor: ofstream outFile("updatedNumbers.txt");
//write the updated numbers to the file
outFile << heading << endl;
outFile << columnHeaders << endl;
outFile << underLines << endl;
heading, columnHeadders and underLines seem to be undefined variables.
for (x=0;x<20; x++)
{
if (int x%2==0)
sample[x] = x+2;
else
sample[x] = x+20;
sample also seems to be undefined.
outFile << num[x] << endl;
num also seems to be undefined. Perhaps you intended it to be the same as sample? Otherwise, you don't seem to have any code to set it to any particular value before you write it out.
Probably worse than any of that is the fact that your heading talks about writing the even numbers from one file to another, but your code doesn't seem to do anything even vaguely similar to that at all.
Well, the heading variable is undeclared, but I guess you already know that....
The error is here:
outFile << heading << endl;
outFile << columnHeaders << endl;
outFile << underLines << endl;
This is the first time you these variables heading, columnHeaders and underLines are mentioned in your program. The compiler complains because they have not been declared anywhere (Should they be int or std::string ore some other type?). Also they won't contain any useful values because nothing has been assigned to them.