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

#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.

Related

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

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");

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 save .txt file in C++? [duplicate]

This question already has answers here:
How to append text to a text file in C++?
(5 answers)
Closed 7 years ago.
I have created a code writing stuff in a .txt file and read from it. But if I close the program and start to write again, it deletes the old text and overwrites it with the new one.
Is there a way to not overwrite existed data?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void check() {
string text;
ifstream file;
file.open("test.txt");
getline(file, text);
if (text == "") {
cout << "There's no data in file" << endl;
} else {
cout << "File contains:" << endl;
cout << text << endl;
}
}
int main() {
check();
string text;
ofstream file;
file.open("test.txt");
cout << "Type some text" << endl;
getline(cin, text);
file << text;
return 0;
}
You need to open the file in 'append' mode like in the following example
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("yourfile.txt", std::ios_base::app);//std::ios_base::app
outfile << "your data";
return 0;
}
You can read here about fstream flagshttp://www.cplusplus.com/reference/fstream/fstream/open/
Keep in mind that in c++ there are several ways to open, save, and read text data to and from a file. It sounds like you opened with with a function (and its options) to always create a new file. One thing you could do is run your program and then close the program and use a text editor to open the file to verify whether the text you wrote to the file is actually there. Also take a look at the code that was provided by Evyatar. That example uses ofstream which allows options for read, write, and append. The "app" parameter tells the program to keep what is already in the file and append any new data that you add in the next run. When testing files where you are appending, be careful you don't end up with a huge file you did not intend to have so large.
In the code that you posted in your revised question, be sure to close the file in your check function and at the end of the program. It is possible to get things hung up if you don't. As a precaution, I usually close a file prior to opening it, just to be sure it is closed with no problems. This practice comes form my days programming in BASIC where it was an essential. If the program crashed, you couldn't open it again until you got it closed. Also, of course, close the file after you're done with it and before the end of the program. Then, when you open it in main, open with the append option.
Please, insert code for next time. If you open file in write mode, than is normal that every time you write to file, the content of file is changed. You need to use append mode.

Reading from a file, only reads text untill it gets to empty space

I managed to successfully read the text in a file but it only reads until it hits an empty space, for example the text: "Hi, this is a test", cout's as: "Hi,".
Removing the "," made no difference.
I think I need to add something similar to "inFil.ignore(1000,'\n');" to the following bit of code:
inFil>>text;
inFil.ignore(1000,'\n');
cout<<"The file cointains the following: "<<text<<endl;
I would prefer not to change to getline(inFil, variabel); because that would force me to redo a program that is essentially working.
Thank you for any help, this seems like a very small and easily fixed problem but I cant seem to find a solution.
std::ifstream file("file.txt");
if(!file) throw std::exception("Could not open file.txt for reading!");
std::string line;
//read until the first \n is found, essentially reading line by line unti file ends
while(std::getline(file, line))
{
//do something line by line
std::cout << "Line : " << line << "\n";
}
This will help you read the file. I don't know what you are trying to achieve since your code is not complete but the above code is commonly used to read files in c++.
You've been using formatted extraction to extract a single string, once: this means a single word.
If you want a string containing the entire file contents:
std::fstream fs("/path/to/file");
std::string all_of_the_file(
(std::istreambuf_iterator<char>(filestream)),
std::istreambuf_iterator<char>()
);

Reading File in C++

I am unable to figure out why my code is not able to open and read a file. What am i missing?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char * const argv[])
{
string line;
ifstream myfile ("input_file_1.txt");
if (myfile.is_open())
{
while (!myfile.eof())
{
getline (myfile,line);
cout << line << endl;
}
}
else
{
cout << "Was unable to open the file" << endl;
}
return 0;
}
The file "input_file_1.txt" is int he same directory as my .cpp file and it has read permissions. I even gave gave it 777 permissions and i was unable to read it.
Can anyone tell me what i am doing wrong? I really cannot figure it out....
Try to use full path for the file
The default location to look for the file is where the executable is , not where the source is.
How and where do you execute your program? From a IDE?
Can you run the program from the same directory where you have your text file.
Another possibility is to use an absolute path to the file.
If you don't specify a path, the library will attempt to load the file from the current directory. You need to make sure that this is where the file is.
Also, you might not be able to open the file if it is opened in an exclusive manner by another program. Ensure that it is not still open in another program such as your editor.
Other Problems:
Explicitly testing for EOF is usually wrong.
The last valid read (getline() here) reads up-to but no past the EOF. You then print the line. Then restart the loop. These test for eof() does not fail (as it has not read past the EOF). You then enter the loop body and attempt to read the next line (with getline()) this fails as there are 0 bytes left to read (thus leaving the value of line in an undefined state). You then print out line (undefined value) and a newline character.
while (!myfile.eof())
{
getline (myfile,line);
cout << line << endl;
}
A correct version of a loop reading a file is:
while (getline (myfile,line))
{
cout << line << endl;
}
This works because the getline() returns a reference to a stream. A stream used in a boolean context (like a while condition) tests to see if the stream is in a bad state (ie it test for EOF and other bad situations) and returns an object that can be used correctyl in the context. If the state of the stream is OK then a successful read has happened and the loop is entered (thus allowing you to print the line).
The binary created from your code (including your cpp) is executed somewhere different from your code is, probably a "bin"-folder. You schould put the file into the same folder as your executable.