File open issues - c++

What would be the reason that this code result in an m_cause of 0 for a file open. Found plenty of reasons that another code will be returned but no reasons for 0.
CFileException fileException;
CFile myFile;
if (myFile.Open("C:\\test\\docs\\test.txt", CFile::modeCreate | CFile::modeWrite, &fileException))
{
TRACE( "Can't open file %s, error = %u\n", "test.txt", fileException.m_cause );
}

CFile::Open() returns none zero upon success, the call in your example does not fail!
Check for !CFile::Open(...)

Return value
Nonzero if the open was successful; otherwise 0. The pError parameter is meaningful only if 0 is returned.
Taken from MSDN (I've linked to the documentation for Visual Studio 2010, but it's the same going back as far as VS2005 and 2003, and probably beyond that).
As per bert-jan's suggestion, you should check for !CFile::Open(...) as in the event that the file does fail to open, you won't actually handle the error.

Related

How can I store the results into a text file?

I'm solving a VRP with SCIP and I wish to export the results of the optimization into a text file. I use the following code but fails when calls the SCIPwriteBestSol function.
FILE* file;
file = fopen("Solution.sol", "w");
SCIP_CALL(SCIPprintBestSol(scip, file, FALSE));
fclose(file);
If the following call works (i.e., prints the solution to console), then your problem comes from the I/O methods. If it fails as well, you have to check your SCIP status, i.e., whether you have a solution at all. If this does not work, I suggest to write to the SCIP mailing list / report a bug.
SCIP_CALL(SCIPprintBestSol(scip, stdout, FALSE));
check the return value of fopen()
as the manual says fopen will return a null pointer if the function call fails
then firstly do it
if ((file = fopen("Solution.sol", "w")) != nullptr)
{
// do your stuff
}

C++: File open call fails

I have the following code in one of my library functions that I am calling many times in a loop. After a large number of iterations I find that open returns -1 which it shouldn't have as the previous iterations worked fine. What may be the cause. How can I get more details on the error.?
int mode;
if (fileLen == 0)
mode = O_TRUNC | O_RDWR | O_CREAT;
else
mode = O_RDWR;
myFilDes = open (fName, mode, S_IRUSR | S_IWUSR);
EDIT:After the end of each iteration I am calling a method that library exposes which internally calls close (myFilDes);
perror is the standard function to map errno to string and print it out to stderr:
if (myFilDes == -1)
perror("Unable to open file: ");
man errno / man perror / man strerror for more info.
Are you closing these handles as well? Do you reach a specific number of open calls before it starts failing?
The errno variable should have additional information as to what the failure is. See: http://linux.die.net/man/2/open

Sharing violation on file which really should be closed

I have an application that modifies an XML file by:
(a) opening it,
(b) creating a temporary file and writing a modified version to it,
(c) closing both files, and
(d) replacing the original file with the temporary file.
When I test it on my laptop running Vista, everything works just as it should. On an embedded PC running XP Professional SP2 with a flash drive instead of a hard disk (which may or may not be relevant), it fails at step (d) with an access violation (error code 5).
If I insert code between steps (c) and (d) to verify that the files are closed, it confirms that they are; if I put in code between steps (c) and (d) to try to delete the original file, it fails with a sharing violation (code 32). If I pause the program at this point and try to delete the file from the GUI, it fails with a sharing violation. If I use systinternals "Process Explorer" at this point, it shows the application still has a handle to the file.
Here is some of the code:
// Open the file which is to be updated:
_wfopen_s(&inStream, m_fileName, L"r, ccs=UTF-8");
// Obtain a suitable temporary filename from the operating system:
TCHAR lpTempPathBuffer[MAX_PATH]; // Buffer to hold temporary file path
TCHAR szTempFileName[MAX_PATH]; // Buffer to hold temporary file name
GetTempPath(MAX_PATH, lpTempPathBuffer);
GetTempFileName(lpTempPathBuffer,
TEXT("TMP"),
0,
szTempFileName);
// Now open a temporary file to hold the updates:
errno_t err = _wfopen_s(&outStream, szTempFileName, L"w, ccs=UTF-8");
if (err == 0)
printf ("Temporary file opened successfully\r\n");
else
printf ("Temporary file not opened; error code %d\r\n", err);
Then the gubbins that modifies the file, and then ...
// Finally, we must close both files and copy the temporary file to
// overwrite the original input file:
int closerr = fclose(inStream);
if (closerr == 0)
printf("Original file closed properly\r\n");
else
printf("Original file not closed properly\r\n");
closerr = fclose(outStream);
if (closerr == 0)
printf("Temp file closed properly\r\n");
else
printf("Temp file not closed properly\r\n");
int numclosed = _fcloseall();
printf("Number of files closed = %d\r\n", numclosed);
// Should be zero, as we've already closed everything manually
if (!DeleteFile(m_fileName))
{
int err = GetLastError();
printf ("Delete file failed, error code was %d\r\n", err);
}
else
printf ("Delete file succeeded\r\n");
if (!MoveFileEx(szTempFileName, m_fileName,
MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH))
{
int err = GetLastError();
printf ("Move file failed, error code was %d\r\n", err);
}
else
printf ("Move file succeeded\r\n");
The output log shows:
"Temporary file opened successfully
Original file closed properly
Temp file closed properly
Number of files closed = 0
Delete file failed, error code was 32
Move file failed, error code was 5"
This makes no sense... Why am I getting a sharing violation on a file which the operating system insists is closed? And is there a reason why this works in Vista but not in XP?
Many thanks for any advice,
Stephen.
One thing to keep in mind with Flash media is that the access times can be much longer, and the file actions are frequently handled asynchronously. Windows may be returning to your code saying that the file is closed before the device driver has actually released it. You go to delete it, and it's really still in use, according to the device driver.
I'd suggest putting a delay in there for testing purposes (say 5-10 seconds), after the file closes and before you try to delete the file. If it works, then what you need to do is to loop on the delete action a couple of times (with a short delay in the loop) and exit the loop when the delete succeeds, or you hit a max # of attempts (say 4-5).
If you still have the same problem, even with a 30 second delay, then the problem probably lies somewhere else.
It seems to be a problem with file permissions. After trying various other things which didn't work, I decided to try opening the file with read/write permissions (i.e with the "r+" attribute rather than "r"), and then overwriting the original file contents with the contents of the temporary file. This time, the "_wfopen_s" command itself failed with error code 13 ("Permission denied"), indicating that the operating system was clearly not willing to let the program tamper with this file under any circumstances.
So I guess I need to frame the question slightly differently: why, when
(a) my application works perfectly as-is in Vista, and
(b) I can freely edit the file when I am using the GUI in XP, and all the file permissions look to be set correctly, and
(c) the program that is trying to modify the file is running from a session that is 'logged in' as the file owner
...can the file not be modified by the program?
Is this a curiosity of XP, or of the fact that it's running on an embedded computer with flash memory? If it were the latter, I'd expect there to be problems when creating brand new temporary files as well, but this seems to work just fine.
I'd once again value any suggestions.
Stephen

c++ fopen is returning a file * with <bad ptr>'s

I copied this code from the libjpeg example and im passing it standard files;
FILE *soureFile;
if ((soureFile = fopen(sourceFilename, "rb")) == NULL)
{
fprintf(stderr, "can't open %s\n", sourceFilename);
exit(1);
}
jpeg_stdio_src(&jpegDecompress, soureFile);
jpeg_read_header(&jpegDecompress, true);
It results in a file pointer that contains no information and therefore breaks on the last line with access violations.
Any ideas?
EDIT: On Tobias' advice the fopen does appear to open the file ok but the jpeg_read_header is in turn failing with the access violation still.
EDIT: After a little more digging
JPEG support with ijg - getting access violation
Use strerror or perror to get exact reason:
FILE *soureFile;
if ((soureFile = fopen(sourceFilename, "rb")) == NULL)
{
perror("fopen failed");
exit(1);
}
"select isn't broken".
If fopen returned a valid file pointer, and jpeg_read_header can't use it, someone between those two statements has done something bad to it.
The only one in between is the jpg_stdio_src call, which wouldn't fail if all it's preconditions are fulfilled.
Bottom line: see why jpg_stdio_src fails. My guess: it needs to be constructed using the jpeg_create_decompress macro.

Error while reading files with native code on windows mobile

I'm new here and my english is not really good. Apologize any inconvenience!
I'm programming an application for windows mobile with native code (MFC). I'm trying to open a file and this is driving me crazy. I've tried to open it in a thousand diferent ways... And I really achieve it, but when I try to read (fread or getline) the program crashes without any explanation:
The program 'x' finalize with code 0 (0x0)
The GetLastError() method, in some cases, returns me a 183.
Then, I put the code I've used to open the file:
std::wifstream file(L"\\Archivos de programa\\Prog\\properties.ini");
wchar_t lol[100];
if (file) {
if(!file.eof()) {
file.getline(lol,99);
}
}
It enters on all the if's, but the getline crashes.
FILE * lol = NULL;
lol = _wfope n(ruta, L"rb");
DWORD a = GetLastError();
if ( lol != NULL )
return 1;
else
return -1;
It returns 1 (correct), and after, in a later getline, it stores trash on the string. However, it doesn't crash!!
fp.open (ruta, ifstream::in);
if ( fp.is_open() ) {
return 1;
}else{
return -1;
}
It enters on the return 1, but when executing the later getline() crashes.
I've debugged the getline() method and it crashes on the library fstream, right there:
if ((_Meta = fget c (_File)) == EOF)
return (false);
In the if. The fgetc(), I supose.
I'm going completely crazy!! I need some clue, please!!
The path of the file is correct. First, because, in theory, the methods open the file, and second, I obtain the path dinamically and it matches.
Emphasize that the fread method also crashes.
Thanks in advance!
P.S.:
Say that when I do any fopen, the method fp.good() returns me FALSE, and the GetLastError returns me 183. By the other hand, if I use fp.fopen(path, ifstream::in); or std::wifstream fp(path); the fp.good(); returns me TRUE, and the GetLastError() doesn't throw any error (0).
A hint: use the Process Monitor tool to see what goes wrong in the file system calls.
The path accepted by wifstream is lacking a drive ("C:" or the like) (I don't know what the ruta variable points to)
Apart from the streams problem itself, you can save yourself a lot of trouble by using the GetProfileString and related functions, when using a windows .ini file.
I'm shooting in the dark here, but your description sounds like a runtime mismatch story. Check that MFC and your project use the same runtime link model (static/dynamic). If you link to MFC dynamically, then the restriction is stricter: both MFC and your project have to use dynamic runtime.
I don't know why, but with the CFile class... it works...
Programming mysteries!
Shooting in the dark too.
Unexplained random crash in MFC often comes from a mismatch message handler prototype.
For example the following code is wrong but it won't generate any warning during compilation and it may work most of the time :
ON_MESSAGE(WM_LBUTTONDOWN, onClick)
...
void onClick(void) //wrong prototype given the macro used (ON_MESSAGE)
{
//do some stuff
}
Here the prototype should be :
LRESULT onClick(WPARAM, LPARAM)
{
}
It often happens when people get confident enough to start modifying manually the message maps.