C++ ofstream System.AccessViolation - c++

I have a problem. I'm writing to a log file, but when I do the application throws:
An unhandled exception of type 'System.AccessViolationException' occurred in ****
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
The code (unmanaged) I'm using is this one:
inline bool writeLog(string message)
{
ofstream myfile;
myfile.open(mStrSource.c_str(), ios::in | ios::out | ios::app);
if(!myfile.is_open())
{
throw "Unable to open the file: " + mStrSource;
}
myfile << "TESTE" << endl;
myfile.close();
return true;
};
When receiving this error, the code points to the _Lock() of file fstream:
virtual void __CLR_OR_THIS_CALL _Lock()
{ // lock file instead of stream buffer
if (_Myfile)
_CSTD _lock_file(_Myfile);
}
Other info:
Developed under VS2010 (Incially the project was Winx32 but now it's Winx64) (.NET Framework 4).
The open() method of ofstream creates the file and the file is writable but throws the exception when try's to write on the file.
Thank you guys in advanced.

Check to make sure your application has rights to write to a file in that location. A standard user in Windows cannot access the whole file system (especially for writing). Either require the app to have admin rights (not recommended for "normal" apps) or write to a place that standard users can get to (e.g. My Documents directory).
Also, make sure the file is not opened for exclusive use by another app like Excel or Word. They have a habit of locking files when opening them.
Another thing to look at is during development, sometimes the .NET runtime/VS debugger will leave a file locked that you were working with after a crash. Try closing/reopening Visual Studio to help with that.

Ok guys,
For future notice, the problem was related to the configuration of the project. When I converted the project from vs2008 to vs2010, from .net 3.5 to .net 4 and from x32 to x64 something didn't quite go right.
So I reverted everything back and converted again in a more controlled environment and now i can open/write/close files without a problem.
Thanks anyway guys.

Related

how i could solve this problem with ifstream

when I run this code its only work with visual studio, in online compiler always tell me "cant opening file"
#include <iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
ifstream input("C:/Users/ACER/Desktop/words.txt");
if (!input.is_open())
{
cout << "cant opening file";
return 0;
}
An online compiler probably cannot open file on your computer using C++ code since that's not how the web works. It would have to route through some Javascript system, which is possible to create, however it seems the creators did not implement that when setting up their compiler.
You might try using file://C:/Users/ACER/Desktop/words.txt and double checking your path. Web browsers use that file:// thing when accessing local file i.e. if you had a web page on your computer it could be like file://C:/Users/ACER/Documents/index.html or something.
If that doesn't work, it just doesn't have the capability to load or save local files like that.
When you were attempting to use the code on an online compiler, most of the time you are actually compiling the code on their server, instead of on your computer.
What that means is that when you are trying to open "C:/Users/ACER/Desktop/words.txt", you are actually attempting to open a text file that is located on their server. And in most cases, you wouldn't be permitted to lookup any directory other than the one you are in. Even if you were permitted to do that for some reason, the chances they also have that text file on their server in the same location is gonna be really low.
Some comments above mentioned that many online compilers often don't have the facility to manipulate files. One that I often use do have the ability to do so in case you were looking for one: https://replit.com/#Ranoiaetep/IndianredSquigglyPrinters
.Note that the working directory is defaulted as your root directory.

c++ filestream problems when opening file in read write mode

Consider the following code snippet:
const char * filePath = "C:/blah.mtt";
fstream fs(filePath, ios::in | ios::out | ios::binary);
if (fs.fail())
std::cout << "Failed to open the file!\n";
the fs.fail() check succeeds always. Does it mean that I can't open a file in both read write mode at the same time?
Creating an empty file first and then running the above code, fs.fail() is false always. What is the rational for such a behavior by the fstream class?
Note: I do have requisite permissions for creating the file. I am trying this on windows 10 using VS2015
Does it mean that I can't open a file in both read write mode at the same time?
No, you can do this, but the question is whether you can create a file by doing so.
Generally you'll need to add the trunc flag (ironically one of the options for how to handle an existing file), or remove the in flag (see here).
Yes, this is a bit of a pain, but it comes from how the original POSIX APIs work. Blame them!
Creating an empty file first and then running the above code, fs.fail() is false always. What is the rational for such a behavior by the fstream class?
You can always open a file that exists (well, subject to permissions). That behaviour makes sense.
the fs.fail() check succeeds always. Does it mean that I can't open a file in both read write mode at the same time?
Refer to #Lightness Races in Orbit's answer for a better explanation.
Creating an empty file first and then running the above code, fs.fail() is false always. What is the rational for such a behavior by the fstream class?
If you look at the constructor definition of fstream you can see that mode defines the way you open it. It has other options like app to append to an existing file. If you open up a file using the following code:
fstream fs(filePath, ios::in | ios::out | ios::binary);
You are saying create a new file if it doesn't exist. Which fails if you pre-created it. You should add the app, ate or truncflag if you want it to open successfully. This depends on what exactly you want to do. However, do note that in between the steps of creating and then opening it doesn't guarantee that the file is still there. You should try to do it in one swoop and let exception handling do its work, since you can never go around the errors anyway.

Error in a C++(files and streams) program for creating a file

I have written this program in order to create a file using fstream and the output should show either the file has been created or not. I have run it on several online compilers like Codechef,C++ shell etc. The compilers has successfully compiled this program but the output is not coming accordingly, instead of saying file created compiler says error in creating file.
Can this be due to development tool?
Following is the code for this program:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("a.txt");
if(!file)
{
cout<<"Error in creating file!!!";
}
else
{
cout<<"File created successfully.";
file.close();
}
}
fstream.open() will fail if the file does not exist.
To create the file if it doesn't exist
file.open("a.txt", ios_base::out);
Or use ofstream
ofstream file;
file.open("a.txt");
The fstream constructor and open function open for read/write by default. The file must already exist to be opened in this mode. Instead, open for write:
file.open("a.txt", ios::out);
Your program's behavior is probably depending upon the operating system. BTW, if you want to learn more about them, read Operating Systems: Three Easy Pieces. Perhaps the current working directory already contains the file to be written or does not have the appropriate permissions (it should be writable to enable file creation). Details are operating system (and perhaps file system) specific. IIRC, some OSes (Windows probably) disallow opening a file which is already opened by some other process.
On Linux, you could use strace(1) to find out what system calls have failed (actually, it tells you all the system calls that have been executed by some given program or process).
This is [probably] not always guaranteed by C++ standards (but see sync_with_stdio), but many C++ standard libraries are above (and compatible with) the C standard library which sets errno(3) (see also strerror(3) and perror(3) ...) on failure; then you might try:
fstream file;
file.open("a.txt", ios::out);
if (!file) {
// perror("a.txt");
cout<<"Error in creating file!!!" << strerror(errno) << endl;
}
Of course, as other answers told you (this & that) you need the correct mode for open...
See also std::system_error

ofstream not creating file (Node.js addon)

I am attempting to create an addon for Node.js that (among other things) writes content to a file inside my C++ class using ofstream.
std::ofstream license_file;
std::string fileContent(*NanAsciiString(args[0]));
license_file.open(PATH);
//file doesn't yet exist, so create it
if(!license_file) {
printf("ERROR: %s (%s)\n", strerror(errno), PATH);
}
license_file << fileContent;
license_file.close();
This works fine if PATH is set to the same directory as my Node.js code (e.g. ./license.txt).
However, ofstream fails to open/create the file in question if it is located anywhere else. For example, using ~/license.txt does not work (note: I'm running OSX).
The error reported is always No such file or directory -- even after I physically create ~/license.txt.
Any ideas why this works in one directory but not others? If it were a permissions issue I would expect a different error message.
For the record, I've seen about 20 other SO questions about "ofstream fails to create file" but passing additional flags into open() has no effect. I have a feeling this is somehow related to running inside Node/V8.
I think the issue is that you need to find out the user directory in a different way than using ~.

Reading a stream in C++

I have the following code:
ifstream initFile;
initFile.open("D:\\InitTLM.csv");
if(initFile.is_open())
{
// Process file
}
The file is not opening. The file does exist on the D: drive. Is there a way to find out exactly why this file cannot be found? Like an "errno"?
You should be able to use your OS's underlying error reporting mechanism to get the reason (because the standard library is built on the OS primitives). The code won't be portable, but it should get you to the bottom of your issue.
Since you appear to be using Windows, you would use GetLastError to get the raw code and FormatMessage to convert it to a textual description.
Answered here I believe: Get std::fstream failure error messages and/or exceptions
The STL is not great at reporting errors. Here's the best you can do within the standard:
ifstream initFile;
initFile.exceptions(ifstream::eofbit|ifstream::failbit|ifstream::badbit);
try
{
initFile.open("D:\\InitTLM.csv");
// Process File
}
catch(ifstream::failure e)
{
cout << "Exception opening file:" << e.what() << endl;
}
In my experience, the message returned by what() is usually useless.
Check the permissions on the root of the D: drive. You may find that your compiled executable, or the service under which your debugger is running, does not have sufficient access privileges to open that file.
Try changing the permissions on the D:\ root directory temporarily to "Everyone --> Full Control", and see if that fixes the issue.