How can I store the results into a text file? - c++

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
}

Related

Refactoring fopen_s

I am attempting to refactor a very old piece of code that generates a log file:
FILE *File = NULL;
errno_t err = fopen_s(&File, m_pApp->LogFilename(), "a+"); // Open log file to append to
if (err == 0)
{
::fprintf(File, "Date,Time,Serial Number,ASIC Voltage,Ink Temp,Heater Temp, Heater Set Point, PSOC Version,");
if (m_ExtraLog)
::fprintf(File, "T1 Temperature,ASIC Temperature,Proc Temperature,Voltage mA");
::fprintf(File, "\n");
fclose(File);
}
The reason for refactoring is that some users report that it is not possible to copy the file that is being produced (they want to copy it so that it can be analysed by a labview program). I read the documentation regarding fopen_s and saw that "Files that are opened by fopen_s and _wfopen_s are not sharable" - is this the cause of my problem? I am unsure because actually, I do not see the copying problem and seem to be able to copy and paste the file without issue. In any case I have replaced it with the recommended _fsopen function like so:
FILE *File = NULL;
if((File = _fsopen(m_pApp->LogFilename(),"a+", _SH_DENYNO))!= NULL)
{
::fprintf(File, "Date,Time,Serial Number,ASIC Voltage,Ink Temp,Heater Temp, Heater Set Point, PSOC Version,");
if(m_ExtraLog)
{
::fprintf(File, "T1 Temperature,ASIC Temperature,Proc Temperature,Voltage mA");
}
::fprintf(File, "\n");
fclose(File);
}
I've given the refactored code to the user but they still report being unable to copy or access the file from labview. I have very limited knowledge of C++ so I am wondering is there any other explanation as to why the file being generated is not able to copied by another process?
Lets have look into doc
Open a file. These are versions of fopen, _wfopen with security enhancements as described in Security Enhancements in the CRT.
Follow by: link
We can read:
Filesystem security. Secure file I/O APIs support secure file access in the default case.
So to fix that, you must change 'file security' to match 'all users/read access'

Why must the file exist when using the 'r+' mode in fopen?

Why add this constraint when your intentions are to both read and write data to the file?
My application wants to open the file in both reading an writing mode. If I use w+ it will destroy the previous contests of the file, but at the same time it will create the file if it doesn't exist.
However if I use the r+ mode, my application will work properly, but if the file doesn't exist it will throw an exception about the nonexistence of the file.
Try something like this. If the first fopen fails because the file does not exist, the second fopen will try to create it. If the second fopen fails there are serious problems.
if((fp = fopen("filename","r+")) == NULL) {
if((fp = fopen("filename","w+")) == NULL) {
return 1;
}
}

How to create a temporary text file in C++?

I'm trying to create a temporary text file in C++ and then delete it at the end
of the program. I haven't had much luck with Google.
Could you tell me which functions to use?
The answers below tell me how to create a temp file. What if I just want to
create a file (tmp.txt) and then delete it? How would I do that?
Here's a complete example:
#include <unistd.h>
int main(void) {
char filename[] = "/tmp/mytemp.XXXXXX"; // template for our file.
int fd = mkstemp(filename); // Creates and opens a new temp file r/w.
// Xs are replaced with a unique number.
if (fd == -1) return 1; // Check we managed to open the file.
write(fd, "abc", 4); // note 4 bytes total: abc terminating '\0'
/* ...
do whatever else you want.
... */
close(fd);
unlink(filename); // Delete the temporary file.
}
If you know the name of the file you want to create (and are sure it won't already exist) then you can obviously just use open to open the file.
tmpnam and tmpfile should probably be avoided as they can suffer from race conditions - see man tmpfile(3) for the details.
Maybe this will help
FILE * tmpfile ( void );
http://www.cplusplus.com/reference/clibrary/cstdio/tmpfile/
Open a temporary file
Creates a temporary binary file, open
for update (wb+ mode -- see fopen for
details). The filename is guaranteed
to be different from any other
existing file. The temporary file
created is automatically deleted when
the stream is closed (fclose) or when
the program terminates normally.
See also
char * tmpnam ( char * str );
Generate temporary filename
A string containing a filename
different from any existing file is
generated. This string can be used to
create a temporary file without
overwriting any other existing file.
http://www.cplusplus.com/reference/clibrary/cstdio/tmpnam/
This may be a little off-topic because the author wanted to create a tmp.txt and delete it after using it, but that is trivial - you can simple open() it and delete it (using boost::filesystem of course).
mkstemp() is UNIX-based. With Windows you use GetTempFileName() and GetTempPath() to generate a path to a temp file. Sample code from MSDN:
http://msdn.microsoft.com/en-us/library/aa363875%28VS.85%29.aspx
On Linux (starting with kernel 3.11), there's flag to open(2) O_TMPFILE that creates a temporary file that doesn't have a name (i.e. it doesn't show up in the filesystem). This has a few interesting features:
No worries about unique names, it's just an inode, there is no name.
No race conditions during creation (e.g. symlink attacks).
No stray files if your app crashes, it's always automatically deleted.
I wonder why most of you guys showed him the C way of doing it instead of the C++ way.
Here's fstream.
Try that, deleting a file is OS depended but you can use boost.filesystem to make things easy for you.
If you need a named file (for example, so you can pass the name to another process, perhaps a compiler or editor), then register a cleanup function that removes the file with atexit(). You can use either C++ <iostream> or C FILE * (<cstdio>) to create the file. The not completely standard but widely available mkstemp() function creates a file and tells you its name as well as returning a file descriptor (a third I/O mechanism); you could use the fdopen() function to convert the file descriptor into a FILE *.
If you don't need a named file a C-style FILE * is OK, then look at tmpfile() as suggested by #Tom.
A clean, portable and non-deprecated way of creating a temporary file is provided by Boost:
auto temporary_file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
Well, assuming you have been successful in creating the temporary file, you can use the remove function to delete it.
The function is declared in stdio.h -
#include <stdio.h>
int remove(const char *pathname);
For example, if you want to delete a file named myfile.txt the code will be
#include<stdio.h>
int main()
{
if(remove("myfile.txt") == -1)
{
fprintf(stderr,"Remove failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
I hope by now, you already know how to create the temp file, so this should resolve your query.
Hope it helps.

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.