CFile file;
CFileException fe;
if (file.Open(strPath, CFile::modeCreate | CFile::modeReadWrite | CFile::typeBinary, &fe) )
{
}
This doesn't work. The file path provided by strPath already exist but it will not open this file and returns with error code 5. If I do remove the CFile::modeCreateflag than the file is opened fine. The documentation says if the file already exists 'CFile::modeCreate' will attach itself to it and truncate it's to zero but in reality it never opens the file in the first place. Is there an issue with my call?
I resolved this. The problem was that the file had 'ready only' attribute set. I changed it to normal before I open it and that fixed it.
SetFileAttributes(strPath, FILE_ATTRIBUTE_NORMAL);
Related
I have this strange bug. I have a program which writes text to the file using the fstream, but the file is not being created and therefore no text is appended. When I debug my code, it shows me this:
create_new_file = {_Filebuffer={_Pcvt=0x0000000000000000 <NULL> _Mychar=0 '\0' _Wrotesome=false ...} }.
But whenever I use ofstream everything works.
Here is the code:
std::fstream create_new_file{ fileName.str()};
std::unique_ptr<std::string> changes = std::make_unique<std::string>("");
std::cin >> *changes;
create_new_file << *changes << "\n";
Here is the code which works:
std::ofstream create_new_file{ fileName.str()};
I have seen a similar post on Stack Overflow but the answer did not resolve my issue. I have tried adding the std::ios::trunc to the fstream but that did not help. But whenever I use ofstream everything works just as expected.
The problem is that for bidirectional file streams the trunc flag must always be explicitly specified, i.e., if you want the file content to be discarded then you must write in | out | trunc as the second argument as shown below.
Thus, to solve the problem change std::fstream create_new_file{ fileName.str()}; to :
//-------------------------------------------------------------------------vvvvvvvvvvvvvvv---->explicitly use trunc
std::fstream create_new_file{ "output.txt", ios_base::in | ios_base::out | ios_base::trunc};
Working demo
This file stream buffer open reference is useful. It shows a table with the different modes and what happens when they are used.
When you open a std::fstream the default mode for the constructor is in | out. If we look that up in the table we see that this will fail if the file doesn't exist.
And you never check for failure (which you always should do).
If you only want to write to the file then use std::ofstream as it will open the files in out mode, which creates the file if it doesn't exist.
If you want to only append to the file, still use std::ofstream but use the mode out | app, which will create the file and make sure all output is appended (written to the end).
I am using MFC CFile.
In windows OS in my application I am locking the file by opening the file with share deny access.
In the same application or process I have to check whether the file is locked or not?
Right now, the only way I know is opening the file and checking GetLastError().
Is there any other solution?
Try to open the file first. If the file exists and is already open without share access, you get a sharing violation
CFileException::sharingViolation.
See CFileException for possible values of CFileException::m_cause
Example:
UINT open_flag = CFile::modeReadWrite | CFile::modeCreate | CFile::modeNoTruncate;
CFileException ex;
if(file.Open(filename, open_flag, &ex))
{
//success
}
else
{
if(ex.m_cause == CFileException::fileNotFound)
{
//file doesn't exit
}
else if(ex.m_cause == CFileException::sharingViolation)
{
//file exists and is locked
}
}
while reading a data from csv file, I got also same errors
In my case,
existed csv file with the same name was open. So, I closed that csv file and it was Okay.
later was the same issue again.
this time, I wrote inappropriate mode while creating
so I changed this code
file.Open(fileName, CFile::modeCreate | CFile::modeReadWrite)
to
file.Open(fileName, CFile::modeCreate | CFile::modeWrite)
In an application I want to be sure that I am writing a brand new (binary) file. In Win32 programming I know I can do this with CreateFile using CREATE_NEW, but I can't work out a pure C++ standard way.
Creates a new file, only if it does not already exist.
If the specified file exists, the function fails and the last-error code is set to ERROR_FILE_EXISTS (80).
If the specified file does not exist and is a valid path to a writable location, a new file is created.
I tried using std::ios::out | std::ios::binary | std::ios::ate then seeing if tellp gave me the start of the file or not, but apart from the obvious case that this would still overwrite an empty file, it also seems to truncate a non-empty file anyway as if I used std::ios::trunc...
This was on VS2013, although I assume this is not a compiler/library bug.
The C++ standard doesn't have an API guaranteeing a new file. When opening an existing file in write-only mode without specifying std::ios_base::app it is truncated (independent on whether std::ios_base::trunc is used). I don't know about Windows but on POSIX this would retain the original inode and processes already having opened the file can still access it.
If it is sufficient to get an open and empty file rather than a new one, omiting std::ios_base::in and std::ios_base::app should do the trick (note that opening an std::fstream or an std::ifstream implicitly adds std::ios_base::in).
For example, if I need to add a sentence to the end of a file. I have to first open the file (e.g. "a.txt"), by
ofstream outfile.open("a.txt");
But whenever I do this, I will overwrite the existing "a.txt" in the same directory. Is it possible to edit the file like first read and then write?
Thank you very much.
You want to open the file in 'append' mode. Passing ios::app to the open method causes the file to be opened in append mode.
f.open("file.txt", ios::app);
See http://www.cplusplus.com/reference/iostream/ios_base/openmode/ for other flags
Try this:
std::ofstream outfile( "a.txt", std::ios_base::app | std::ios_base::ate );
Various references:
http://www.cplusplus.com/reference/iostream/ofstream/ofstream/
http://www.cplusplus.com/reference/iostream/ofstream/open/
http://msdn.microsoft.com/en-us/library/aa277521(v=vs.60).aspx
http://msdn.microsoft.com/en-us/library/aa266859(v=vs.60).aspx
I am opening a file with ifstream to check if it exists. Then I close it and open it with ofstream to write to it, and I think setting ios::trunc flag allows me to overwrite it.
However I'd like the ability to keep the file open if it exists, but I used an ifstream to open it so does that mean I can't write to the file till I close and re-open using fstream or ofstream? I didn't use fstream to begin with because that wouldn't tell me if the file was already there or not.
Just open a read-write fstream on the file. You can test if the file previously existed (and was non-empty) by seeking to the end and seeing if you're at a non-zero offset. If so, the file existed, and you can do whatever with it. If not, the file didn't exist or was empty. Assuming you don't need to distinguish between those two cases, you can then proceed as if it did not exist.
For example:
// Error checking omitted for expository purposes
std::fstream f("file.txt", std::ios::in | std::ios::out);
f.seekg(0, std::ios::end)
bool didFileExist = (f.tellg() > 0);
f.seekg(0, std::ios::beg);
// Now use the file in read-write mode. If didFileExist is true, then the
// file previously existed (and has not yet been modified)
The setting ios::trunc erases previous contents of the file.
Try opening the file without this setting; with only the 'write' setting.
this is touching very serios problem - race conditions - what if somebody manages to do something with this file between closing and reopening? unfortunately iostream does not provide any means of resolving that issue - you can use cstdio FILE. If you want to turncate file if exists or create new one if not use fopen(name, "w"). If you want to turncate file if it exists or fail otherwise, then it seems standard library has nothing to offer, and you should go to other libraries or platform specific functions like OpenFile in windows.h