I can't get the ofstream function to work - c++

Hello and sorry if the answer is clear to those out there. I am still fairly new to programming and ask for some guidance.
This function should write just one of the three string parameters it takes in to the txt file I have already generated. When I run the program the function seems to work fine and the cout statement shows the info is in the string and does get passes successfully. The issue is after running the program I go to check the txt file and find it is still blank.
I am using C++17 on visual studio professional 2015.
void AddNewMagicItem(const std::string & ItemKey,
const std::string & ItemDescription,
const std::string &filename)
{
const char* ItemKeyName = ItemKey.c_str();
const char* ItemDescriptionBody = ItemDescription.c_str();
const char* FileToAddItemTo = filename.c_str();
std::ofstream AddingItem(FileToAddItemTo);
std::ifstream FileCheck(FileToAddItemTo);
AddingItem.open(FileToAddItemTo, std::ios::out | std::ios::app);
if (_access(FileToAddItemTo, 0) == 0)
{
if (FileCheck.is_open())
{
AddingItem << ItemKey;
std::cout << ItemKey << std::endl;
}
}
AddingItem.close(); // not sure these are necessary
FileCheck.close(); //not sure these are necessary
}
This should print out a message onto a .txt file when you pass a string into the ItemKey parameter.
Thank you very much for your help and again please forgive me as I am also new to stackoverflow and might have made some mistakes in formatting this question or not being clear enough.
ADD ON: Thank you everyone who has answered this question and for all your help. I appreciate the help and would like to personally thank you all for your help, comments, and input on this topic. May your code compile every time and may your code reviews always be commented.

As mentioned by previous commenters/answerers, your code can be simplified by letting the destructor of the ofstream object close the file for you, and by refraining from using the c_str() conversion function.
This code seems to do what you wanted, on GCC v8 at least:
#include <string>
#include <fstream>
#include <iostream>
void AddNewMagicItem(const std::string& ItemKey,
const std::string& ItemDescription,
const std::string& fileName)
{
std::ofstream AddingItem{fileName, std::ios::app};
if (AddingItem) { // if file successfully opened
AddingItem << ItemKey;
std::cout << ItemKey << std::endl;
}
else {
std::cerr << "Could not open file " << fileName << std::endl;
}
// implicit close of AddingItem file handle here
}
int main(int argc, char* argv[])
{
std::string outputFileName{"foobar.txt"};
std::string desc{"Description"};
// use implicit conversion of "key*" C strings to std::string objects:
AddNewMagicItem("key1", desc, outputFileName);
AddNewMagicItem("key2", desc, outputFileName);
AddNewMagicItem("key3", desc, outputFileName);
return 0;
}

Main Problem
std::ofstream AddingItem(FileToAddItemTo);
opened the file. Opening it again with
AddingItem.open(FileToAddItemTo, std::ios::out | std::ios::app);
caused the stream to fail.
Solution
Move the open modes into the constructor (std::ofstream AddingItem(FileToAddItemTo, std::ios::app);) and remove the manual open.
Note that only the app open mode is needed. ofstream implies the out mode is already set.
Note: If the user does not have access to the file, the file cannot be opened. There is no need to test for this separately. I find testing for an open file followed by a call to perror or a similar target-specific call to provide details on the cause of the failure to be a useful feature.
Note that there are several different states the stream could be in and is_open is sort of off to the side. You want to check all of them to make sure an IO transaction succeeded. In this case the file is open, so if is_open is all you check, you miss the failbit. A common related bug when reading is only testing for EOF and winding up in a loop of failed reads that will never reach the end of the file (or reading past the end of the file by checking too soon).
AddingItem << ItemKey;
becomes
if (!(AddingItem << ItemKey))
{
//handle failure
}
Sometimes you will need better granularity to determine exactly what happened in order to properly handle the error. Check the state bits and possibly perror and target-specific
diagnostics as above.
Side Problem
Opening a file for simultaneous read and write with multiple fstreams is not recommended. The different streams will provide different buffered views of the same file resulting in instability.
Attempting to read and write the same file through a single ostream can be done, but it is exceptionally difficult to get right. The standard rule of thumb is read the file into memory and close the file, edit the memory, and the open the file, write the memory, close the file. Keep the in-memory copy of the file if possible so that you do not have to reread the file.
If you need to be certain a file was written correctly, write the file and then read it back, parse it, and verify that the information is correct. While verifying, do not allow the file to be written again. Don't try to multithread this.
Details
Here's a little example to show what went wrong and where.
#include <iostream>
#include <fstream>
int main()
{
std::ofstream AddingItem("test");
if (AddingItem.is_open()) // test file is open
{
std::cout << "open";
}
if (AddingItem) // test stream is writable
{
std::cout << " and writable\n";
}
else
{
std::cout << " and NOT writable\n";
}
AddingItem.open("test", std::ios::app);
if (AddingItem.is_open())
{
std::cout << "open";
}
if (AddingItem)
{
std::cout << " and writable\n";
}
else
{
std::cout << " and NOT writable\n";
}
}
Assuming the working directory is valid and the user has permissions to write to test, we will see that the program output is
open and writable
open and NOT writable
This shows that
std::ofstream AddingItem("test");
opened the file and that
AddingItem.open("test", std::ios::app);
left the file open, but put the stream in a non-writable error state to force you to deal with the potential logic error of trying to have two files open in the same stream at the same time. Basically it's saying, "I'm sorry Dave, I'm afraid I can't do that." without Undefined Behaviour or the full Hal 9000 bloodbath.
Unfortunately to get this message, you have to look at the correct error bits. In this case I looked at all of them with if (AddingItem).

As a complement of the already given question comments:
If you want to write data into a file, I do not understand why you have used a std::ifstream. Only std::ofstream is needed.
You can write data into a file this way:
const std::string file_path("../tmp_test/file_test.txt"); // path to the file
std::string content_to_write("Something\n"); // content to be written in the file
std::ofstream file_s(file_path, std::ios::app); // construct and open the ostream in appending mode
if(file_s) // if the stream is successfully open
{
file_s << content_to_write; // write data
file_s.close(); // close the file (or you can also let the file_s destructor do it for you at the end of the block)
}
else
std::cout << "Fail to open: " << file_path << std::endl; // write an error message
As you said being quite new to programming, I have explicitly commented each line to make it more understandable.
I hope it helps.
EDIT:
For more explanation, you tried to open the file 3 times (twice in writing mode and once in reading mode). This is the cause of your problems. You only need to open the file once in writing mode.
Morever, checking that the input stream is open will not tell you if the output stream is open too. Keep in mind that you open a file stream. If you want to check if it is properly open, you have to check it over the related object, not over another one.

Related

Why is stream::ignore not working as intended?

As far as I know, stream.ignore(n, 'n') should ignore an (n) amount of characters or if ā€˜\nā€™ is reached, and skip over to the next line, however, when I run the next code:
// include...
void insertInfo(int info) {
std::fstream stream("infoFile.txt"); // Open the file
while (!stream.eof()) {
std::string a{};
// getline(stream, a); <--- Tried this, didn't work either
stream.ignore(99, '\n');
} // Skip to the last line without any number, in theory
std::cout << info << std::endl; // Check if the output it's correct (Which is)
stream << info; // Insert the info
stream.close(); // Close the file
}
void main() //Main
{
std::cout << "Enter your name, followed by the info you want to add to infoFile:" << std::endl;
std::string info, temp = "";
std::getline(std::cin, temp); // Get the info input
std::stringstream sstream;
sstream << temp;
sstream >> temp >> info; // Remove the name keeping only the info
temp = ""; // ^
std::string::size_type sz;
insertInfo(stoi(info, &sz)); // Convert info string into an integer and insert it in infoFile
}
The console prints out the "info" correct value, however, when I check info.txt, in which I previously wrote a '0' on, you don't see any change.
I tried removing the "ignore" function and it overwrites the 0, which is exactly what I was trying to prevent.
I also tried using "getline" function but the same thing happens.
What is the error here?
Problem
Cannot write to file.
Why
void insertInfo(int info) {
std::fstream stream("infoFile.txt"); // Open the file
Opens file with default permissions, which includes reading. The C++ Standard says I should expect "r+" behaviour and the C Standard says a file opened with "r+" behaviour must exist in order to be read (Someone please add a link if you have one). You cannot create a new file. This is problem 1. The Asker has dealt with this problem by providing a file.
Note: take care when working with files via relative paths. The program's working directory may not be where you think it is. This is problem 1a. It appears that the Asker has this taken care of for the moment.
while (!stream.eof()) {
Common bug. For more details see Why is iostream::eof inside a loop condition considered wrong? In this case since all you're looking for is the end of the file, the fact that the file hasn't been opened at all or has encountered any read errors is missed. Since a file in an error state can never reach the end of the file this quickly becomes an infinite loop. This is problem 2.
std::string a{};
// getline(stream, a); <--- Tryied this, didn't work neither
stream.ignore(99, '\n');
Always test IO transactions for success. This call can fail unchecked.
} // Skip to the last line without any number, in theory
Assuming nothing has gone wrong, and since we're not checking the error state assuming's all we can do, the file has reached the end and is now in the EOF error state. We can't read from or write to the stream until we clear this error. This is problem number 3 and likely the problem the Asker is struggling with.
std::cout << info << std::endl; // Check if the output it's correct (Wich is)
stream << info; // Insert the info
This can fail unchecked.
stream.close(); // Close the file
This is not necessary. The file will be closed when it goes out of scope.
}
Solution
void insertInfo(int info) {
std::fstream stream("infoFile.txt"); // Open the file
while (!stream.eof()) {
stream.ignore(99, '\n');
} // Skip to the last line without any number, in theory
std::cout << info << std::endl; // Check if the output it's correct (Wich is)
stream.clear(); // Added a call to clear the error flags.
stream << info; // Insert the info
stream.close(); // Close the file
}
Now we can write to the file. But let's improve this shall we?
void insertInfo(int info) {
std::fstream stream("infoFile.txt");
while (stream.ignore(99, '\n')) // moved ignore here. now we ignore, then test the result
{
}
stream.clear();
stream << info << '\n'; // added a line ending. Without some delimiter the file
// turns into one big number
}
Note that this isn't exactly kosher. If any ignore fails for any reason, we bail out and possibly write over data because the code blindly clears and writes. I'm not spending much time here trying to patch this up because we can get really, really simple and solve the problem of creating a non-existent file at the same time.
void insertInfo(int info) {
std::fstream stream("infoFile.txt", std::ios::app);
stream << info << '\n';
}
Two lines and pretty much done. With app we append to the file. We do not need to find the end of the file, the stream automatically points at it. If the file does not exist, it is created.
Next improvement: Let people know if the write failed.
bool insertInfo(int info) {
std::fstream stream("infoFile.txt", std::ios::app);
return static_cast<bool>(stream << info << '\n');
}
If the file was not written for any reason, the function returns false and the caller can figure out what to do. The only thing left is to tighten up the stream. Since all we do is write to ti we don't need the permissiveness of a fstream. Always start with the most restrictive and move to the least. This helps prevent some potential errors by making them impossible.
bool insertInfo(int info) {
std::ofstream stream("infoFile.txt", std::ios::app);
return static_cast<bool>(stream << info << '\n');
}
Now we use an ofstream and eliminate all the extra overhead and risk brought in by the ability to read the stream when we don't read the stream.

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.

When will ofstream::open fail?

I am trying out try, catch, throw statements in C++ for file handling, and I have written a dummy code to catch all errors. My question is in order to check if I have got these right, I need an error to occur. Now I can easily check infile.fail() by simply not creating a file of the required name in the directory. But how will I be able to check the same for outfile.fail() (outfile is ofstream where as infile is ifstream). In which case, will the value for outfile.fail() be true?
sample code [from comments on unapersson's answer, simplified to make issue clearer -zack]:
#include <fstream>
using std::ofstream;
int main()
{
ofstream outfile;
outfile.open("test.txt");
if (outfile.fail())
// do something......
else
// do something else.....
return 0;
}
The open(2) man page on Linux has about 30 conditions. Some intresting ones are:
If the file exists and you don't have permission to write it.
If the file doesn't exist, and you don't have permission (on the diretory) to create it.
If you don't have search permission on some parent directory.
If you pass in a bogus char* for the filename.
If, while opening a device file, you press CTRL-C.
If the kernel encountered too many symbolic links while resolving the name.
If you try to open a directory for writing.
If the pathname is too long.
If your process has too many files open already.
If the system has too many files open already.
If the pathname refers to a device file, and there is no such device in the system.
If the kernel has run out of memory.
If the filesystem is full.
If a component of the pathname is not a directory.
If the file is on a read-only filesystem.
If the file is an executable file which is currently being executed.
By default, and by design, C++ streams never throw exceptions on error. You should not try to write code that assumes they do, even though it is possible to get them to. Instead, in your application logic check every I/O operation for an error and deal with it, possibly throwing your own exception if that error cannot be dealt with at the specific place it occurs in your code.
The canonical way of testing streams and stream operations is not to test specific stream flags, unless you have to. Instead:
ifstream ifs( "foo.txt" );
if ( ifs ) {
// ifs is good
}
else {
// ifs is bad - deal with it
}
similarly for read operations:
int x;
while( cin >> x ) {
// do something with x
}
// at this point test the stream (if you must)
if ( cin.eof() ) {
// cool - what we expected
}
else {
// bad
}
To get ofstream::open to fail, you need to arrange for it to be impossible to create the named file. The easiest way to do this is to create a directory of the exact same name before running the program. Here's a nearly-complete demo program; arranging to reliably remove the test directory if and only if you created it, I leave as an exercise.
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#include <cstring>
#include <cerrno>
using std::ofstream;
using std::strerror;
using std::cerr;
int main()
{
ofstream outfile;
// set up conditions so outfile.open will fail:
if (mkdir("test.txt", 0700)) {
cerr << "mkdir failed: " << strerror(errno) << '\n';
return 2;
}
outfile.open("test.txt");
if (outfile.fail()) {
cerr << "open failure as expected: " << strerror(errno) << '\n';
return 0;
} else {
cerr << "open success, not as expected\n";
return 1;
}
}
There is no good way to ensure that writing to an fstream fails. I would probably create a mock ostream that failed writes, if I needed to test that.

Unable to write file in C++

I'm trying to to the most basic of things .... write a file in C++, but the file is not being written. I don't get any errors either. Maybe I'm missing something obvious ... or what?
I thought there was something wrong with my code, but I also tried a sample I found on the net and still no file is created.
This is the code:
ofstream myfile;
myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt");
myfile << "Writing this to a file.\n";
myfile.close();
I've also tried creating the file manually beforehand, but it's not updated at all.
I'm running Windows 7 64bit if that has got something to do with this. It's like file-write operations are completely forbidden and no error messages or exceptions are shown.
You need to open the file in write mode:
myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt", ios::out);
Make sure to look at the other options for that second argument, as well. If you're writing binary data you'll need ios::binary for example.
You should also be checking the stream after opening it:
myfile.open(...
if (myfile.is_open())
...
Update:
AraK is right, I forgot that an ofstream is in write mode by default, so that's not the problem.
Perhaps you simply don't have write/create permissions to the directory? Win7 defaults a lot of directories with special permissions of "deny all". Or perhaps that file already exists and is read-only?
Start off by turning that slash around.
Even Windows understands the slash being the other way around.
ofstream myfile("C:/Users/Thorgeir/Documents/test.txt");
You could test if there are any errors:
if (!myfile)
{
std::cout << "Somthing failed while opening the file\n";
}
else
{
myfile << "Writing this to a file.\n";
myfile.close();
}
Make sure the directory exists.
If the file exists make sure it is writeable (by you)
Check the directory you are writing into is writeable (by you)
Have you read about UAC (User Account Control) and UAC Virtualization / Data Redirection in Windows Vista and 7? It's possible that your file is actually in the Virtual Store.
User Account Control Data Redirection
Your example output directory is in Users, so I wouldn't think this would be the issue, but it's a possibility worth mentioning and something that can be very frustrating if you're not looking out for it!
Hope this helps.
This code should catch any error. Most likely it's a permissions thing if any errors are encountered. Make sure you can read/write to the folder you're creating the file in.
#include "stdafx.h"
#include <fstream>
#include <iostream>
bool CheckStreamErrorBits(const std::ofstream& ofile);
int _tmain(int argc, _TCHAR* argv[]) {
std::ofstream ofile("c:\\test.txt");
if(ofile.is_open()) {
CheckStreamErrorBits(ofile);
ofile << "this is a test" << std::endl;
if(CheckStreamErrorBits(ofile)) {
std::cout << "successfully wrote file" << std::endl;
}
}else {
CheckStreamErrorBits(ofile);
std::cerr << "failed to open file" << std::endl;
}
ofile.close();
return 0;
}
//return true if stream is ok. return false if stream has error.
bool CheckStreamErrorBits(const std::ofstream& ofile) {
bool bError=false;
if(ofile.bad()) {
std::cerr << "error in file stream, the bad bit is set" << std::endl;
bError=true;
}else if(ofile.fail()) {
std::cerr << "error in file stream, the fail bit is set" << std::endl;
bError=true;
}else if(ofile.eof()) {
std::cerr << "error in file stream, the eof bit is set" << std::endl;
bError=true;
}
return !bError;
}
Update:
I just test my code under Windows 7 Enterprize and it failed the first time (fail bit was set). Then I turn off User Account Control (UAC) and tested again and it wrote the file. That is probably the same problem you're seeing. To turn off UAC go to:
Control Panel (view by Small icons) | User Accounts | Change User Account Control settings. Set it to Never notify then click OK button. You will have to restart for the changes to take affect.
I'm curious how to make it work with UAC on, i'll look into that.
Try this:
if( ! myfile)
{
cerr << "You have failed to open the file\n";
//find the error code and look up what it means.
}
Use FileMon and look for failed WriteFile calls from your process.