I have an application for which GUI is written in C# UWP and accessing the file logic is written in C++ DLL. The DLL should open a file to read data from it. I am trying to access the file from its location. When I call inFile.open("D:\\File\\readFile.txt", ios::in)
the value returned is NULL.
To check if there is any problem with the file path, I have created a console application to access the file using the same way and it worked. What could be the problem?
fstream inFile;
inFile.open(filePath, ios::in);
if (!inFile.is_open())
{
/* Display unable to read file*/
return;
}
/* Perform operation on file */
inFile.close();
Related
I am trying to stream a .zip file to hardware using mfc c++. The hardware needs the file still in .zip format when sent over because it will do the unpacking itself.
I have been unable to find a class or method to grab a .zip file and stream it over.
Most searches lead me to questions about unzipping or zipping using c++ which is of no use in my particular case.
Any advice? Has anyone ran into this situation?
The following code snippet reads the 100 first bytes of a file into a buffer using CFile:
CFile f;
if (f.Open(L"path_to_your_file", CFile::modeRead))
{
char buffer[100];
f.Read(buffer, sizeof buffer);
f.Close();
}
else
{
// handle error
DWORD error = GetLastError();
// error number in error
...
}
This is more or less all you need. Google for the documentation of CFile.
You should be able to figure out the rest.
The format of the file you're reading is irrelevant. You just need to read the contents of your file and send it to the hardware.
For completeness, I'm using C++ in Visual Studio 2012 under Windows 7.
I have some basic file reading code:
Defined in class:
std::ifstream iniFileHandle;
Method in question:
FileLoader::FILE_STATUS FileLoader::loadFile(const std::string& fullpathandfilename)
{
if (fullpathandfilename.empty())
{
iniFileStatus = FILE_NOT_SPECIFIED;
}
else // parameter has 'something'...
{
if (!doesFileExist(fullpathandfilename))
{
iniFileStatus = FILE_NOT_FOUND;
}
else // file found...
{
iniFileHandle.open(fullpathandfilename, std::ios::in);
if (!iniFileHandle.is_open()) // something went wrong
{
iniFileStatus = FILE_CANNOT_LOAD; // <== HOW TO TEST?
}
else // file opened!
{
iniFileStatus = FILE_OPEN;
}
}
}
return iniFileStatus;
}
All this works fine but I'm having difficulty getting coverage with Google Unit Tests.
What i'm missing is a way to simulate/create a scenario where is_open() fails.
I've tried:
read only files
the 'exe' being currently run
a file opened in another application
but they all open.
Is this error condition actually possible to occur? If so, how can I mimic the failure so I can test it?
As mentioned in the comments, trying to open a directory will cause is_open() to return false. The cases you tried all succeed because you open the file as read-only (std::ios::in, which is also the default for an ifstream).
I've tried:
a file opened in another application but they all open.
This happens because file is opened in share mode which allows reading for others. You need to open file in exclusive file access mode. To achieve it, if you use MSVS, you could pass the third parameter int _Prot to the ifstream, otherwise you could use CreateFile().
To emulate the problem you could open file exclusively used by Windows, e.g:
c:\pagefile.sys
create a any file, and set its permission as read only, and in your code try to open this file for writing
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
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.
I have some c++ code in a node.js function that opens a file like this and reads it into a buffer and then closes it.
ifstream inputFile(source.c_str(), ios::in | ios::binary);
inputFile.read(buffer, results.st_size);
inputFile.close();
Then I manipulate the file in some way and attempt to write it back to the same location. I get the following error code and message: "Text file busy". I know there is no other process touching the file. If I rename the file to some random name, and rename it back, then I am able to overwrite the file.