c++ iostream - output file is not created - c++

I added some commands to produce an output file in methods of a given class. This worked perfectly well, and output file was produced during execution. Now that I made major changes to the code (but not at all to the output file commands), I am not producing output correctly anymore? Where can this come from? The code I changed seems not have any connexion to output commands. Constructor looks like
solverMethod::solverMethod(solverInput*inp_):solverMethod(inp_)
{
ndim = m_input->getNbParams();
bestFuncEval = DBL_MAX;
NMAX = m_input->getMaxIter();
FTOL = m_input->getTolerance();
NITER = 0;
logMode = true;
osOutput.open("F://Output.txt") ;
}
where member boolean logMode decide whether comments are active or not.
In different methods, I have code like
if(logMode)
{
osOutput << "\n";
osOutput << " - - BUILD ";
osOutput << "\n";
osOutput << "INITIAL";
osOutput << "\n";
for(int k=0;k<npts;k++)
{
for(int j=0;j<m_ndim;j++)
{
osOutput << s_[k][j] ;
osOutput << ", ";
}
}
osOutput << "\n";
}
to produce comments
and then I have at the end of major method:
// ....
osOutput.close();
return true;
}
Do you have any further info

What is the status of the stream after the open? You almost always
want to check whether the open succeeded (and whether all of the
writes succeeded after the close). You might try something like:
osOutput.open(...);
if ( !osOutput.is_open() ) {
std::cerr << "Cannot create ..., error was: " << strerror( errno);
}
This will give you more information about what is wrong.

Related

How can I check if an option is a flag with CLI11?

I am using the CLI11 library (link) for parsing of command line arguments of my programm.
Now I want to print information about the options of my program to stdout.
It seems that flags added via App::add_flag(...) are stored as Options internally as well, but I need to distinguish them in my output.
How can I determine which option is a flag?
Here is a simplified example:
std::string file, bool myflag;
CLI::App *command = app.add_subcommand("start", "Start the program");
command->add_option("file", file, "This is a file option")->required();
command->add_flag("--myflag", myflag);
print_description(command);
...
std::string print_description(CLI::App* command) {
for (const auto &option : command->get_options()) {
result << R"(<option name=")" << option->get_name() << R"(" description=")" << option->get_description()
<< R"(" type=")";
if (/*option is a flag*/) {
result << "flag";
} else {
result << "option";
}
result << R"("/>)";
}
return result.str();
}
According to this issue: https://github.com/CLIUtils/CLI11/issues/439, the function Option::get_expected_min will always return 0 for flags.
So it's possible to check it like this:
if (option->get_expected_min() == 0) {
result << "flag";
} else {
result << "option";
}

std::ofstream : Writing to a file using append and out flags

Below is a simple class which attempts to write an integer to a file. The mode of writing the file is to append characters at the end of the file (In this mode, file should be created if it doesn't exist)
#include <iostream>
#include <fstream>
class TestFileStream
{
private:
std::ofstream* _myFileStream;
bool isFileOpen;
public:
TestFileStream():isFileOpen(false)
{
_myFileStream = new std::ofstream("TestFile.txt", std::ios_base::out | std::ios_base::app );
isFileOpen = _myFileStream->is_open();
if( !isFileOpen )
{
std::cout << "Unable to open log file" << std::endl;
std::cout << "Good State: " << _myFileStream->good() <<std::endl;
std::cout << "Eof State: " << _myFileStream->eof() <<std::endl;
std::cout << "Fail State: " << _myFileStream->fail() <<std::endl;
std::cout << "Bad State: " << _myFileStream->bad() <<std::endl;
}
else
{
std::cout << "Opened log file" << std::endl;
}
}
~TestFileStream()
{
_myFileStream->close();
delete _myFileStream;
_myFileStream = nullptr;
}
void WriteFile( unsigned number )
{
if ( isFileOpen )
{
(*_myFileStream) << "Number: " << number << std::endl;
}
}
};
int main()
{
// Number of iterations can be multiple.
// For testing purpose, only 1 loop iteration executes
for( unsigned iter = 1; iter != 2; ++iter )
{
TestFileStream fileWriteObj;
fileWriteObj.WriteFile( 100+iter );
}
return 0;
}
When I execute the above code, I get following log output:
Unable to open log file
Good State: 0
Eof State: 0
Fail State: 1
Bad State: 0
This seems like trivial task, but I am not able to find out whats causing the failure. Note that this question is most likely related to the following question
Just to summarize the comments, there is nothing wrong about the code you posted (apart from the rather unconventional new ostream ;) )
Note however that opening files may fail for a number of reasons (Permissions, file in use, disk unavailable, the file does not exist, the file exists...). That is why you must always test it.
If you tried to run the above code in an online emulator, then chances are file IO is disabled. Which would explain why you get that the streams fail-bit is set.

ofstream/fstream simply will not work, no matter what solution is tried

Okay guys, I've tried everything I can think of. I'm passing in a file name into this function. A little context: hash_table is an already initialized and filled vector with key pairs, and the 'value' part of the pair is a Linked List that has the field "bucket_size". When I use cout to check if these fields are actually being accessed, they are; even the debugger lists them as being filed into the output stream. I have flush() and close() in there, but it doesn't write anything to the file. Returns true, indicating no errors in the stream. Anyone have nay ideas?
string line;
std::ofstream ofs;
if(ofs.is_open())
ofs.close();
ofs.open(filename);
if (ofs.is_open())
{
cout << "File Opened" << endl;
for (double i = 0; i < hash_table.capacity(); ++i)
{
ofs << "Bucket Number " << i;
if (hash_table[i].value != NULL)
ofs << " Bucket Size: " << hash_table[i].value->bucket_size << endl;
else
ofs << " Bucket Size: 0" << endl;
ofs.flush();
}
cout << "closing file stream" << endl;
ofs.flush();
ofs.close();
if (ofs.good())
return true;
else
return false;
}
else
{
cout << "File not opened" << endl;
return false;
}
}
You're almost certainly examining the wrong file. Remember that relative paths are relative to the working directory of the process, which is not necessarily the same as where the executable lives on disk.
I compiled and ran it by the console and now it works, with no edits made. It seems my IDE doesn't like something in the code. Regardless, thank you everyone for the response.s

setxkbmap returns 65280 when executed from system call

I am sending
std::string cmdStr = "setxkbmap us";
int res = system( cmdStr.c_str() );
and the result is
res: 65280
What can be the problem?
That value indicates that the child process exited normally with a value of 255.
This could happen if:
/bin/sh couldn't find setxkbmap. (note: I might be wrong on this one. On my PC, /bin/sh returns 127 in that case.)
setxkbmap couldn't open the X server at $DISPLAY, including if DISPLAY is unset
I'm sure that there are many other possibilities. Check stdout for error messages.
When interpreting the return value from system on Linux, do this:
#include <sys/wait.h>
int res = system(foo);
if(WIFEXITED(res)) {
std::cout << "Normal exit: " << WEXITSTATUS(res) << "\n";
} else {
if(WIFSIGNALED(res)) {
std::cout << "Killed by signal #" << WTERMSIG(status);
if(WCOREDUMP(res)) {
std::cout << " Core dumped";
}
std::cout << "\n";
} else {
std::cout << "Unknown failure\n";
}
}

CORBA AMI call not producing callback?

I'm modifying the stock quoter example from the wustl CORBA release. The assignment is to implement a reply handler for the StockFactory class that handles calls to get_stock()
Here's my FactoryHandler implementation:
FactoryHandler_i.h:
#ifndef TAO_TUTORIALS_QUOTER_AMI_CLIENT_FACTORYHANDLER_I_H
#define TAO_TUTORIALS_QUOTER_AMI_CLIENT_FACTORYHANDLER_I_H
#include "QuoterS.h"
class Stock_Factory_Handler_i : public POA_Quoter::AMI_Stock_FactoryHandler
{
public:
Stock_Factory_Handler_i (int *response_count, ::Quoter::Stock_var& result);
void get_stock (::Quoter::Stock_ptr ami_return_val);
void get_stock_excep (::Messaging::ExceptionHolder * excep_holder);
private:
int *response_count_;
::Quoter::Stock_var& result_;
};
#endif /* TAO_TUTORIALS_QUOTER_AMI_CLIENT_HANDLER_I_H */
FactoryHandler_i.cpp:
#include "FactoryHandler_i.h"
#include "ace/streams.h"
Stock_Factory_Handler_i::
Stock_Factory_Handler_i (int *response_count, ::Quoter::Stock_var& result)
: response_count_ (response_count), result_ (result)
{
}
void
Stock_Factory_Handler_i::get_stock (::Quoter::Stock_ptr ami_return_val)
{
cout << "storing result" << endl;
result_ = ami_return_val;
(*this->response_count_)++;
}
void
Stock_Factory_Handler_i::get_stock_excep (::Messaging::ExceptionHolder * excep_holder)
{
// We ignore the exception, but this counts as a response, otherwise
// the application would not finish.
cerr << "Exception raised while getting stock"
<< endl;
(*this->response_count_)++;
}
And the client.cpp, from just before the part where changes have been made:
// ...
// Create and activate the handler...
int response_count = 0;
Single_Query_Stock_Handler_i handler_i (&response_count);
Quoter::AMI_Single_Query_StockHandler_var handler =
handler_i._this ();
// Create and activate the factory handler...
Quoter::Stock_var result;
Stock_Factory_Handler_i factory_handler_i (&response_count, result);
Quoter::AMI_Stock_FactoryHandler_var factory_handler =
factory_handler_i._this();
// Send all the requests, careful with error handling
int request_count = 0;
for (int i = 2; i != argc+1; ++i) {
try {
// Get the stock object
cout << "looking up stock symbol " << argv[i] << endl;
factory->sendc_get_stock (factory_handler.in (), argv[i]);
sleep(3); // wait for a response
cout << "converting result" << endl;
Quoter::Single_Query_Stock_var stock =
Quoter::Single_Query_Stock::_narrow (result.in ());
cout << "checking result" << endl;
CORBA::Any any;
any <<= stock;
CORBA::TypeCode_var tc = any.type();
cout << tc->kind() << endl;
if (CORBA::is_nil (stock.in ())) {
cerr << "Cannot get single query interface for <"
<< argv[i] << ">" << endl;
continue;
}
cout << "reading result" << endl;
stock->sendc_get_price_and_names (handler.in ());
request_count++;
}
catch (Quoter::Invalid_Stock_Symbol &) {
cerr << "Invalid stock symbol <"
<< argv[i] << ">" << endl;
}
}
while (response_count < 2 * request_count // multiply by 2 because both handlers increment response_count
&& orb->work_pending ()) {
orb->perform_work ();
}
// ...
When running the client, the output is:
looking up stock symbol MSFT
converting result
checking result
14
Cannot get single query interface for <MSFT>
(The 14 is the typecode for Stock, that's only for debugging)
Notably missing from the above is the "storing result" message that's supposed to be printed in the FactoryHandler's get_stock() callback method. I'm at a loss as to why, since the sendc_get_stock() method doesn't produce any (immediate) errors and is basically just a copy of the StockHandler's code, and from there it's the responsibility of the AMI/ORB interface to make the callback. But the original example (with a StockHandler only) works fine.
What am I doing wrong (and how do I fix it)?
EDIT: another bit of information: on the server side, StockFactory's get_stock() method does get called.
Sorry, I've no aswer for you. But a hint, ask your question at TOA's maling list at http://www.cs.wustl.edu/~schmidt/ACE-mail.html
HTH
I think that your problem is that work_pending returns true only if the ORB has immediate work to do, so it returns false in the time after your client sent his request and before the server sends his reply.
To validate that, simply remove the && orb->work_pending() condition from the loop, and use the version of perform_work that takes a timeout argument.