ofstream keeps giving me the last line of the function instead of showng everything - c++

so I have been trying to figure out a way to have a function enter whatever is written in a file and to output into a Sha-256 function. maybe why do I want to do that? Simple enough I am trying to just teach myself how things work in c++, however it displays the last line for the function ofstream. this is my main function
ifstream input ("/home/findme/Desktop/text.txt"); // opens text.txt file.
string s;
while (getline (input, s))
{
// loop to read every line one by one of the file.
string c = s; // enters function to be converted.
string output1 = sha256(c); // gives back the value of the string.
cout << "sha256('"<< c << "'):" << output1 << endl; //displays the results.
ofstream outfile ("/home/findme/Desktop/result.txt");
outfile << "sha256('"<< c << "'):" << output1 << endl;
outfile.close();
}
ok so just an insight of what happens, it reads the context of the file named text.txt in this file there is 3 lines which are (test, test2, test3). so it reads one line and sends it to the function and it returns then it does it for the second line and so on. Once it hits the last line the cout function reads this
sha256('test'):9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
sha256('test2'):60303ae22b998861bce3b28f33eec1be758a213c86c93c076dbe9f558c11c752
sha256('test3'):fd61a03af4f77d870fc21e05e7e80678095c92d808cfb3b5c279ee04c74aca13
and that's correct. there is no problem whatsoever with the cout function but when I try to put it in an external file named result.txt it displays
sha256('test3'):fd61a03af4f77d870fc21e05e7e80678095c92d808cfb3b5c279ee04c74aca13
That's is the problem, it seems like all it does is writes the last function. I tried to change the placing of the ofstream as in outside the loop or before the cout function and it gives the same issue, I also tried with a loop and it gives the same issue. It just repeats the sha256('test3').
Now I know that its obviously something really easy to fix but im not seeing, therefore can someone please help me? I want it to display exactlty what the cout displays. (there are no error messages and it compiles without a problem). Thank you

You are creating your ofstream outfile in the loop. Meaning it's recreated each iteration through the loop. If you move this line to the top of your sample code it should work:
ofstream outfile ("/home/findme/Desktop/result.txt");

Related

C++ (Visual Studio): Recieving nothing when trying to read input from a .txt file

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line = "test";
ifstream myfile("example.txt");
myfile.open("example.txt");
if (myfile.is_open())
{
cout << line << "\n";
cout << "File Opened\n";
getline(myfile, line);
cout << line;
while (getline(myfile, line))
{
cout << line << '\n';
cout << "test";
}
myfile.close();
}
else cout << "Unable to open file";
//return 0;
//getchar();
}
Apologies in advance if this has been answered, but while I've found several answers that are very close to what I need, I can't find an answer to this specific problem.
I'm new to Visual Studio, but have dabbled in c++ in the past. I'm trying to read in data from a text file and (for now) simply print that back out with cout. But, I'm not seeing any results.
At first I figured I just had my txt file in the wrong place - and I did. Initially I would receive the line "Unable to open file", indicating that the file could not be opened. So I moved it around and found out where Visual Studio wanted me to put the file.
So now I successfully see the "File Opened\n" line get printed to the screen, followed by nothing. I thought I might be using getline wrong, but if I replace the file input "myfile" with a "cin" instead, getline will happily read in keyboard input all day, so that's not it either.
So I've put in some test cout statements that print out the value of my string, line. The first one prints out "test" as it should. Then I read in a line of the txt file to that string variable, and when I cout it again I get nothing. It's a blank string.
Also, the line " cout << "test"; " From within the loop does NOT print either. So the loop's not even happening, it seems.
So, as near as I can tell, the program is able to find my textfile, example.txt. But it's not actually seeing the contents within.
The contents of the textfile (and what I'd like the program to print out) are as follows:
"This is the first line
This is the second line
Third
Fourth
Fifth"
Any and all help is much appreciated.
Figured it out.
What went wrong is this line:
ifstream myfile("example.txt");
I don't know exactly why, but since I specify the file to open in the next line down ( myfile.open("example.txt"); ), specifying the filepath in the ifstream declaration caused the issue.
I don't entirely get it, as others have said that the code runs fine for them. But this seems to work, anyway.
If there's any reason why I shouldn't use this solution, please let me know.
you might want to take a look at your file open
"myfile.open("example.txt");" i found if you don't give a file path weird things happen.
myfile.open("c:\test\example.txt");
is the adjustment I made to the code and it work like a dream.

why I cant read a file to an integer vector?

well! I have a text file including some integer values and non-integers like character strings and white spaces so I want only to read integers values so I used a vector of integers but when I read the file the opining is ok but it seems the first input fails thus breaks the loop!!!
here is my main example:
ifstream in("file.txt");
if(in.fail())
cout << "opening failed!" << endl;
//opening is fine!
int value;
vector<int> v;
while(in >> value) // the problem here; it fails why?
{
cout << "ok"; // not printed
v.push_back(value);
}
cout << v.size() << endl; // 0??!!
this is the content of file.txt:
32 43 24 32
15 23
57
77 81
if I make a vector of chars it's ok but I want only to use one of integers
*** I already used a code like this and worked fine but now I don't know what happened??!!! it's really annoting
any help, comment, tip is welcome and appreciated
This line:
while(in >> value)
says while I can read integers...
But in the post this may not be true - you are not handling this case.
Either read stuff that is not integers and handle it. Or just read strings and then decide what to do.
In addition
cout << "ok"; // not printed
is because it is buffered.
Do this
cout << "ok" << flush; // printed
excuse me first for annoying you with nonsense question. finally I managed to discover the error:
in my main folder of project I unintentionally created a winrar file input.rar then I didn't remove it but rename it to input.txt it's ok I opened it manually and removed some unreadable characters. then I put inside it the content above of integers then my c++ application succeeds in opening it but can't read it.
*now I removed it input.txt which was input.rar and created a new document text input.txt and now everything is good!!!
thank you for your collaboration. and this post may help someone else.
* don't create rar file or other formats then rename them to be text files and try to read them via your c++ fstream because it'll fail in fact it'll produce an error-prone which looks impossible to solve

ofstream creating file but not writing to it in C++

I am writing an MFC program that has a dialog with an "Export" button that will take all of the data that has been entered into the file and export it to a .txt (at some point I want to change this to a .msg file...but that's a question for another day).
However, when I click the button, it creates the file but doesn't write anything inside the file. For testing, I removed everything except just a simple literal string and even that isn't printing. Here is the current code for that event: The myfile.flush() statement is leftover from when I had a loop that I was trying to print to the file.
void CEHDAHTTimerDlg::OnBnClickedExport()
{
// in this function, we want to export the items to a text file
std::ofstream myfile("TodayTime.txt");
myfile.open("TodayTime.txt");
if (myfile.is_open())
{
myfile << "The average call time is ";
myfile.flush();
myfile.close();
}
else
{
SetDlgItemText(IDC_EXPORT, L"Export Unsuccessful! -- No File");
}
}
Is there anything you all can think of that could be causing this? I've been at it for a few hours trying different things, like utilizing a myfile.write() function instead. I've searched a lot around here, reddit, and google in general trying to find out why this isn't writing.
I appreciate your help.
EDIT:
Okay, calling the myfile constructor the way that I did, by including the file name, went ahead and did what open file would have done
Thanks for your help!
commenting out the redundant "open" solves it.
#include <iostream>
#include <fstream>
int main()
{
// in this function, we want to export the items to a text file
std::ofstream myfile("TodayTime.txt");
// myfile.open("TodayTime.txt");
if (myfile.is_open())
{
myfile << "The average call time is ";
myfile.flush();
myfile.close();
}
else
{
std::cerr << "didn't write" << std::endl;
}
}
I strongly suspect that you're invoking undefined behaviour by opening and already-open stream.
Here is the explanation:
The call to myfile.open("TodayTime.txt"); will fail because the stream is already associated with the file, setting the failbit.
The call to is_open() will succeed, as the file is open.
Then the call to streaming operator << will fail (because of the failbit).
this is because myfile << "The average call time is "; not working
to fix that
std::ofstream myfile;
myfile.open("TodayTime.txt",std::ios:app) //app for appending you can use trunc for
//truncating file
//for flushing content's of existing file use myfile.flush();
if (!data_pack.is_open())
{
std::cerr << "unable to open the file for writing";
}
myfile << "some stuff tho write you can replace the string with variable"
<<std::endl; //for next line
//at last close file
myfile.close();

How to extract specific substring from getline function in C++?

I'm fairly new to C++ so please forgive me if my terminology or methodology isn't correct.
I'm trying to write a simple program that:
Opens two input files ("infileicd" and "infilesel").
Opens a single output file "list.txt".
Compares "infilesel" to "infileicd" line by line.
If a line from "infilesel" is found in "infileicd", it writes that line from "infileicd" to "list.txt", effectively making a separate log file.
I am using the getline() function to do this but have run into trouble when trying to compare each file line. I think it might be easier if I could use only the substring of interest to use as a comparison.
The problem is that there are multiple words within the entire getline string and I am only really interested in the second one. Here are two examples:
"1529 nic1_mau_op_mode_3 "8664afm007-01" "1" OUTPUT 1 0 LOGICAL 4 4136"
"1523 pilot_mfd_only_sel "8664afm003-02" "1" OUTPUT 1 0 LOGICAL 4 4112"
"nic1_mau_op_mode_3" and "pilot_mfd_only_sel" are the only substrings of interest.
It would make it a lot easier if I could only use that second substring to compare but I don't know how to extract it specifically from the getline() function. I haven't found anything suggesting it is impossible to do this, but if it is impossible, what would be an alternative method for extracting that substring?
This is a personal project so I'm under no time contstraints.
Any assistance is greatly apprecated in advance. Here is my code (so far):
int main()
{
//Open the file to write the selected variables to.
ofstream writer("list.txt");
//Open the selected variabels file to be read.
ifstream infilesel;
infilesel.open("varsel.txt");
//Open the icd file to be read.
ifstream infileicd;
infileicd.open("aic_fdk_host.txt");
//Check icd file for errors.
if (infileicd.fail()){
cerr << "Error opening icd.\n" << endl;
return 1;
}
else {
cout << "The icd file has been opened.\n";
}
//Check selected variables file for errors.
if (infilesel.fail()){
cerr << "Error opening selection file.\n" << endl;
return 1;
}
else {
cout << "The selection file has been opened.\n";
}
//Read each infile and copy contents of icd file to the list file.
string namesel;
string nameicd;
while(!infileicd.eof()){
getline(infileicd, nameicd);
getline(infilesel, namesel);
if (nameicd != namesel){ //This is where I would like to extract and compare the two specific strings
infileicd; //Skip to next line if not the same
} else {
writer << nameicd << namesel << endl;
}
}
writer.close();
infilesel.close();
infileicd.close();
return 0;
}
So, based on what we discussed in the comments, you just need to toss the stuff you don't want. So try this:
string namesel;
string nameicd;
string junk;
while(!infileicd.eof()){
// Get the first section, which we'll ignore
getline(infileicd, junk, ' ');
getline(infilesel, junk, ' ');
// Get the real data
getline(infileicd, nameicd, ' ');
getline(infilesel, namesel, ' ');
// Get the rest of the line, which we'll ignore
getline(infileicd, junk);
getline(infilesel, junk);
Basically, getline takes a delimiter, which by default is a newline. By setting it as a space the first time, you get rid of the first junk section, using the same method, you get the part you want, and then the final portion goes to the end of the line, also ignoring it.

C++ Binary File method is removing content from the file?

I have an assignment where I am writing input on various things (in the form of structs) and then writing to a binary file. I have to be able to both read and write to the file while the program is open. One of the methods needs to print out all of the clients in the binary file. It seems to be working, except whenever I call that method, it seems to erase the contents of the file and prevent more from being written to it. Here's the applicable snippets:
fstream binaryFile;
binaryFile.open("HomeBuyer", ios::in | ios::app | ios::binary);
The same file is supposed to be usable between times you run the program, so I should open it with ios::app, correct?
Here's the method to add an entry:
void addClient(fstream &binaryFile) {
HomeBuyer newClient; //Struct the data is stored in
// -- Snip -- Just some input statements to get the client details //
binaryFile.seekp(0L, ios::end); //This should sent the write position to the
//end of the file, correct?
binaryFile.write(reinterpret_cast<char *>(&newClient), sizeof(newClient));
cout << "The records have been saved." << endl << endl;
}
And now the method to print all the entries:
void displayAllClients(fstream &binaryFile) {
HomeBuyer printAll;
binaryFile.seekg(0L, ios::beg);
binaryFile.read(reinterpret_cast<char *>(&printAll),sizeof(printAll));
while(!binaryFile.eof()) { //Print all the entries while not at end of file
if(!printAll.deleted) {
// -- Snip -- Just some code to output, this works fine //
}
//Read the next entry
binaryFile.read(reinterpret_cast<char *>(&printAll),sizeof(printAll));
}
cout << "That's all of them!" << endl << endl;
}
If I step through the program, I can input as many clients as I want, and it will output them all the first time I call displayAllClients(). But as soon as I call displayAllClients() once, it seems to clear out the binary file, and any further attempts at displaying clients gives me no results.
Am I using seekp and seekg incorrectly?
From what I understand, this should set my write position to the end of the file:
binaryFile.seekp(0L, ios::end);
And this should set my read position to the beginning:
binaryFile.seekg(0L, ios::beg);
Thanks!
Pasting comment in as this resolved the issue.
You need to call binaryFile.clear() before seekp() and seekg() if EOF is set, otherwise they won't work.
This is the documentation for ios::app
ios::app
All output operations are performed at the end of the file, appending the
content to the current content of the file. This flag can only be used in
streams open for output-only operations.
Since this is homework, I'll let you draw your own conclusions.