C++ Trouble opening a file for output - c++

So I am working on a program for class in which we have to open two different text files to retrieve the appropriate text to be displayed in the console. My code is not opening the file and keeps outputting the else statement ".txt file cannot be open". I've tried several different ways to open the file but with no luck. Any help here would be greatly appreciated.
//
// main.cpp
// PunchLine program
// Page 896 Problem 3
//
//
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
//File stream objects
fstream inFile;
string line;
//Open joke file to read lines to console
inFile.open("joke.txt", ios::in);
if (inFile.is_open())
{
//Read lines from file to console
while (getline(inFile, line))
{
cout << line << endl;
inFile.close();
}
}
else
cout << "joke.txt file cannot be open.\n";
//Open punchline file to read last line joke to console
inFile.open("punchline.txt", ios::in);
if (inFile.is_open())
{
//Read last line from file to console
inFile.seekp(-52L, ios::end);
getline(inFile, line);
}
else
cout << "punchline.txt file cannot be open.\n";
return 0;
}

When declaring an input file use
ifstream inFile;
Also make sure the input file is in the same folder as your .exe
Edit: http://www.cplusplus.com/doc/tutorial/files/ also, this link should help with working with files.
Edit 2: I already posted this in a comment, but I'll just add it to the official answer: "Change your while loop as well. Instead of the if test, use while(inFile.is_open()) and then use your getline statement inside the loop. Because right now your code reads like while get this line from the file is true cout line. So it might not even be doing the while loop."

I don't think you should close the file inside the while loop. Otherwise, your file gets closed after only the first line is read in. Move the close statement outside the loop. Same for the second block.
if (inFile.is_open())
{
//Read lines from file to console
while (getline(inFile, line))
{
cout << line << endl;
}
inFile.close();
}
else
cout << "joke.txt file cannot be open.\n";

Check that your file exist. If it does, check whether you have the correct path when you open it (check if your .txt files are in the same directory as your .exe file, or specify the full path in your code). If yes, check if the files are read-only.

use
if(!infile)
{
cout<<"cannot open file";
}

I think you need to flush the screen. Once you have flushed and closed the stream. The next time you run an application it should open the file.
e.g.
inFile.flush();
inFile.close();

Related

How to write and read a file with `fstream` simultaneously in c++?

I'm trying to write some text to a file and then read it using only 1 fstream object.
My question is very similar to this question except for the order of the read/write. He is trying to read first and then write, while I'm trying to write first and then read. His code was able to read but did not write, while my code is able to write but not read.
I've tried the solution from his question but it only works for read-write not write-read.
Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fileObj("file.txt", ios::out|ios::in|ios::app);
// write
fileObj << "some text" << endl;
// read
string line;
while (getline(fileObj, line))
cout << line << endl;
}
The code writes some text to file.txt successfully but it doesn't output any text from the file. However, if I don't write text to the file (remove fileObj << "some text" << endl;), the code will output all text of the file. How to write first and then read the file?
This is because your file stream object has already reached the end of the file after the write operation. When you use getline(fileObj, line) to read a line, you are at the end of the file and so you don't read anything.
Before beginning to read the file, you can use fileObj.seekg(0, ios::beg) to move the file stream object to the beginning of the file and your read operation will work fine.
int main()
{
fstream fileObj("file.txt", ios::out | ios::in | ios::app);
// write
fileObj << "some text" << endl;
// Move stream object to beginning of the file
fileObj.seekg(0, ios::beg);
// read
string line;
while (getline(fileObj, line))
cout << line << endl;
}
Although this answer doesn't qualify for your requirement of "reading and writing a file simultaneously", keep in mind that the file will most likely be locked while being written to.
Here the simple example to write and read the file.
Hope it will help you.
#include<fstream>
using namespace std;
int main ()
{
ofstream fout ("text.txt"); //write
ifstream fin ("text.txt"); // read
fout<<"some text";
string line;
while (fin>> line) {
cout<<line;
}
return 0;
}

Problems with reading a .txt file

I am looking for an answer to my question, but i didn't find it in any other place.
I'm trying to read from a .txt file, that is located in the same directory as my project files.
I wrote this simple code:
ifstream file("file.txt");
std::string line;
std::getline(file, line);
cout << line;
...but unfortunately, nothing happened, not even an error or crashing.
Upon exploring a little further... even if I change the name of the txt("file") file, to the name of a file that doesn't exist, nothing happens.
What am I missing?
How do you know there were no errors? You did not check.
#include <cerrno>
and then
ifstream file("file.txt");
if (file) // is the file readable?
{
std::string line;
if (std::getline(file, line)) // did we manage to read anything?
{
cout << line;
}
else
{
cout << "File IO error";
}
}
else
{
cout << "error opening file: " << strerror(errno);
}
performs rudimentary checking.
if your error is due to opening file then provide full path to the file and check.
in your code you are reading the first line so if it is a white space then you can see nothing as output.
you must to iterate over each line until the last line (reaching the end of file EOF).
// let's say your file is "test.txt" which is located in D\\MyDB
// ifstream file("file.txt");
ifstream file("D:\\MyDB\\test.txt"); // use full path instead and check manully whether the file is there or not
std::string line;
if(file.fail())
cout << "Opening file failed!" << endl;
else
while(std::getline(file, line))
{
cout << line;
}
if it works when providing the full path then your current path is not the same as your project.
you can change the current directory using some API so if you are on windows then use: SetCurrentDirectory(path); and on linux use: chdir(sDirectory.c_str());
** I mean compilers not OS

Unable to print text from file

I'm trying to write a simple program that will print the contents of a text file one line at a time. However, whenever I run the program i just get a blank screen. I'm certain the file I am trying to read contains text over several lines. Any help as to why this isn't working would be super helpfull.
bool show() {
string line;
ifstream myfile;
myfile.open("tasks.txt", ios::app);
while (!myfile.eof()) {
getline (myfile, line);
cout << line << endl;
}
myfile.close();
return true;
}
The problem might be that you are using ios::app with ifstream (input stream), which makes no sense.
According to this,
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.
Try this:
std::string line;
ifstream myfile ("tasks.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
std::cout << line << std::endl;
}
myfile.close();
}
Did you check return value of myfile.isopen()? Perhaps the file isn't there or you don't have read permission.
Oh yes, I missed that - the append flag. Should be ios::in

Visual C++ - Cannot open text file

Simple program to open up a file and read it's contents. Then a test at the end to see if I did in fact get the information. Every time I run it it tells me that it cannot open the file. I will post the contents of SaleSlips below. Why isn't it opening the file? It is also attempting to delete the file every run as well.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
struct SaleSlip{
char name[20];
int prodID;
double value;
};
void main(){
fstream slips;
SaleSlip sales[17];
slips.open("SaleSlips.txt", ios::in);
if(slips.eof()){
cout << "Cannot open file - SaleSlips.txt"<< endl;
system("pause");
exit(2);
}
int i = 0;
while(!slips.eof()){
slips.getline(sales[i].name, ' ');
slips >> sales[i].prodID;
slips.ignore(5, ' ');
slips >> sales[i].value;
slips.ignore(80, ' ');
i++;
}
cout << sales[1].value;
slips.close();
system("pause");
}
Eric 1 200000.00
Sookie 2 200.00
Sookie 4 200.50
You're opening the stream in output mode by using ios::out. Use ios::in to read from it.
You've got a lot of other issues, too. IE:
-The if(!slips.eof()) after the file open will always cause an exit unless the file is empty.
-In your while loop, you are (probably accidentally) attempting to write the prodID and value into the slips file using <<. Use >> to read from a stream and << to write to it.
You have two problems:
You're opening the file for output (writing)
slips.open("SaleSlips.txt", ios::out);
Useios::in instead for input (reading)
slips.open("SaleSlips.txt", ios::in);
Next, you're immediately testing for !eof(), which is the wrong logic.
if(!slips.eof())
You don't want to be at eof() when opening the file for input. eof() is end of file. When first opening the file for input you want to be at the beginning of the file; being at eof() is a bad thing. Your code should error out if eof() is true, not if it's false:
if(slips.eof()) {
// It's an error if we're starting at eof()
}

C++ text decoder only taking one line from a text file

Im working on a two part program that uses an encoder do encode a text file then a decoder to decode the text file. However i cannot get my decoder to read the whole text file it just reads the first line. How do i fix this, ive played around with the loops but it is not helping me.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
string lineFromFile;
fin.open("secret.txt");
if (!fin.good()) throw "I/O error";
fout.open("secret.txt", ios::app);
if (!fout.good()) throw "I/O error";
while (fin.good())
{
getline(fin, lineFromFile);
for (int i = 0; i < lineFromFile.length(); i++) // for each char in the string...
lineFromFile[i]--; // bump the ASCII code by 1
fout << lineFromFile << endl;
}//while
fin.close();
fout.close();
return 0;
}
You are closing the stream in the first iteration (i.e., after reading the first line). Then you open the output stream to write the first line. Only then do you reach the end of the while-loop, at which time fin.good() cannot be true anymore since you closed fin.
The loop should contain only the reading and writing. Opening done before the loop, closing done after.
Additional suggestion: Use proper indenting, it helps understanding the control flow.
I think the problem might be that you are reading and writing from the same file: secret.txt. I do not know what the expected behaviour is but when I ran the code it was infinite, which makes some sense as you are appending.
Try changing the ouput stream, fout, to a different file name.
The while loop that currently processes the file will process a final invalid read as you do not check if getline() was successful until the loop condition. I would suggest changing to:
for (;;)
{
getline(fin, lineFromFile);
if (!fin.good())
{
break;
}
for (int i = 0; i < lineFromFile.length(); i++)
lineFromFile[i]--;
fout << lineFromFile << endl;
}
Perhaps that because another file handle,fout, accesses the file to which fin is tied, fin is closed as a side-effect. Either that, or because fout appends to the file, the file pointer is pointed to the end of the file, and so because there is no more input to read, the loop ends.
(These are hypotheses; I am not familiar enough with the specifics of C++ I.O. to conclusively say what is happening.)
If you are supposed to replace the original file with an encoded version, I recommend setting the file tied to fout to a temporary file for the duration of your code above, closing both fin and fout, and then copying the file associated with fout over the file associated with fin.
Otherwise, just tie fout to a different filename than fin, such as "encoded.txt".