Reading File in C++ - 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.

Related

unable to read and write using same fstream object in c++

I'm trying to use same fstream object for first write the file and after that read the file.
when I'm using below code then the codes of writing the file is working but I'm getting junk output instead of texts which written in the file.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
fstream file;
file.open("test.txt",ios::in|ios::out| ios::trunc);
if (!file) {
cout << "Error";
}
else {
cout << "success";
file <<"\n\n1st Line\n 2nd line \n 3rd line\n";
string filecontent;
while (file.good()) {
getline(file, filecontent);
cout << filecontent << endl;
}
}
return 0;
}
Output
This code has two separate problems. The first (which others have already pointed out to at least some degree) is that your loop isn't detecting the end of the file correctly. In fact, almost any time you use while (!file.eof()) or while (file.good()), it's going to be a mistake--it won't detect end of file at the right time, so (for example) when you reach the end of the file, you won't detect it at the right time, and you'll see the last item in the file appear to be read twice before the loop exits.
In addition to that, however, you have a problem in that you're writing to the file, then immediately trying to read. That's simply not allowed--you want to do a seek any time you switch between reading and writing.
In this case, you have a bit of a further problem. Since you've just written data into the file, your file's current position is at the end of the file. So even if you could just start reading without seeking, you'd start reading from the end of the file. That, of course, would immediately fail.
So you also really need to seek back to the beginning of the file to be able to read it back in.
So, the big changes here are adding a line like: file.seekg(0); after you finish writing, but before you start to try to read that data back in, and then changing your reading loop to something like:
while (getline(file, filecontent)) {
cout << filecontent << endl;
}
One last point: although it's not going to make a big difference in this case, I'd advise using "\n" instead of std::endl. std::endl writes a new-line and flushes the file buffer. When you're writing to the screen it won't make any real difference, but when writing to a normal file flushing the buffer unnecessarily can and will slow your code substantially (10x slower is pretty common).

getline(stream, string) from example is rejected by editor(VS2019)

The example is taken from:
[http://www-h.eng.cam.ac.uk/help/tpl/languages/C++/1AComputing/Mich/index.php?reply=extraReadingfromfiles#extraReadingfromfilesanchor][1]
I wrote the code without the while loop to read file, the example used getline(stream, strgvar), but this is not admited by the editor
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string message;
ifstream fin; // variable to store information about a file
fin.open("s.txt"); // trying to open file for reading
// next line would try to check if file has been opened succesfully
if (not fin.good())
{
cout << "\n\t Couldn't open the s file." << endl;
cout << "\n\t It needs to be in the same folder as your program."
<<endl;
return 1; // In the main function this line quits from the
whole program.
}
// we have menaged to open the file. Now we'll read a line from the file into the string
while (message!="works!")
{
fin >> message;
cout << message << " ";
}
//getline(fin,message);
}
My questions is why the line now commented is rejected ?
fin>>message;
The stream extraction operator '>>' is used when you want to read a single word from file.
Find complete explanation at : https://www.google.com/amp/s/www.geeksforgeeks.org/cpp-program-read-file-word-word/amp/
While
getline(fin,message);
In this, a full line from the file will be read in message variable. It will continue reading and assigning file contents till a '\n' (Line Deliminator) character does not appear. And thats why you getline() statement is rejected.
For complete explanation visit : http://www.cplusplus.com/forum/windows/48212/
Your program is expected to read a word at a time. And to accomplish this, fin>>mesage is used. Basically stream extraction operator read the contents till a space appears, and hence it is used to read single word.
And if you still want to use getline (), then add a third parameter to your function call as space character ' '.
Like
getline(fin,message,' '); // and done
Basically the third parameter of getline function is Deliminator, by default it is '\n', but if you want to define your own Deliminator, you can do so by providing third parameter. It will read the contents of file till the Deliminator does not occurs while reading.
To use std::getline() include <string> in the header.
https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/2whx1zkx(v=vs.100)
istream also has a getline. More details here
https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-6.0/aa277361(v=vs.60)

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.

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

getline() returns empty line in Eclipse but working properly in Dev C++

Here is my code:
#include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main() {
string line;
ifstream inputFile;
inputFile.open("input.txt");
do {
getline(inputFile, line);
cout << line << endl;
} while (line != "0");
return 0;
}
input.txt content:
5 9 2 9 3
8 2 8 2 1
0
In Enclipse, it goes to infinite-loop. I'm using MinGW 5.1.6 + Eclipse CDT.
I tried many things but I couldn't find the problem.
Since you are on windows try:
} while (line != "0\r");
The last line is stored as "0\r\n". The \n is used as the line delimiter by getline so the actual line read will be "0\r"
or
you can convert the dos format file to UNIX format using command
dos2unix input.txt
Now your original program should work. The command will change the \r\n at the end of the line to \n
Also you should always do error checking after you try to open a file, something like:
inputFile.open("input.txt");
if(! inputFile.is_open()) {
cerr<< "Error opening file";
exit(1);
}
It will create an infinite loop if no line contains exactly 0. For example 0\n is not the same thing as 0. My guess is that that is your problem.
EDIT: To elaborate, getline should be discarding the newline. Perhaps the newline encoding of your file wrong (i.e. windows vs. unix).
Your main problem is working directory.
Because you are specifying a file using a relative path it searches for the file from the current working directory. The working directory can be specified by your dev environment. (Note: The working directory is not necessarily the same directory where the executable lives (this is a common assumption among beginners but only holds in very special circumstances)).
Though you have a special end of input marker "0" you should also check that the getline() is not failing (as it could error out for other reasons (including beady formatted input). As such it is usually best to check the condition of the file as you read it.
int main()
{
string line;
ifstream inputFile;
inputFile.open("input.txt");
while((getline(inputfile, line)) && (line != "0"))
{
// loop only entered if getline() worked and line !="0"
// In the original an infinite loop is entered when bad input results in EOF being hit.
cout << line << endl;
}
if (inputfile)
{
cout << line << endl; // If you really really really want to print the "0"
// Personally I think doing anything with the termination
// sequence is a mistake but added here to satisfy comments.
}
return 0;
}