Portable output to null stream in Fortran - fortran

I'd like to implement a verbosity level flag in a Fortran program in the following way. The code would use statements
write (level1, *) 'This will be shown always'
write (level2, *) 'This will be shown sometimes'
and the streams level1, level2 and higher would either be equal to output_unit or correspond to /dev/null (on Unix), depending on the value of the verbosity flag provided by the user.
However, /dev/null is not platform independent. I could try to detect Windows manually and work with NUL there, but I don't want to write platform-specific code. Is there a platform-independent way of writing to an output sink with write in Fortran?

I've made my earlier comment into an answer so we can tick this question off ...
Fortran doesn't provide a platform independent way to send output into the void. If I wanted the facility I might write a little platform-dependent code, and wrap it into a module so I never had to look at it again.

Related

Fortan fully portable I/O unformatted files

I have found several questions and answers about this, but among "stream", "recl", HDF,etc. I am a bit lost ( I am quite a newbie ).
I apologize if there is somewhere a plain answer to my question.
This is my problem: I want to insert into an existing Fortran code a "WRITE" statement that produces an unformatted file that I can subsequently read with another post-processing Fortran code that I have written. With portability I mean that I can do this regardless the compiler and compilation flags used and, ideally, between different platforms (computers). Is this possible? How? If not, what are the compromises that I must accept?
If the anwer is supported by a detailed, but not too complicated, explanation, it would be highly appreciated.
p.s.
I want to use unformatted files because they are lighter and the I/O operations should be faster than with formatted files. Correct?
Update #1
From a comment it seems that it is not strictly possible to obtain an unformatted file which is portable to different machines. Therefore, let us assume I want to use a single machine. I am using ifort and gfortran. If with Fotran90 is not possbile, I think I can use Fortran2003. For me it is a bit complicated to control the compilation flags used to compile the original code, but if it is necessary I can work to control that aspect too.

How to control stdin echo in C++?

In Linux, I can use tcsetattr, but I want to write a portable C++ program that can turn echo of cin on and off (for entering a password). Is there something in std::io* that supports this?
Unfortunately there is no portable way to disable console echo, so you have to use OS specific API. You can use preprocessor to write portable program, but you would have to write separate code for supported OS and wrap it into #ifdef condition. Another solution would be to use portable library if such one exists, that would do this under the hood for you.
No, there is not. C/C++'s IO libraries are based around the "stream" model, where input comes from some random source of characters (generally the console) and output is similarly sent to some random character target. In a sense, it isn't C/C++ doing the echoing at all -- it's the console system -- so there's no way for it to control whether the echoing occurs.

Using standard output from C library in C++ application

I have code written in C, which I'm working towards making a library from which I can access functions from other languages.
I am presently writing a C++ client to this code, to figure out what changes are necessary to provide support for including my library into a C++ application.
Normally, the C-based binary analyzes some input, and it then outputs its data to stdout through a series of fprintf statements.
Is there a way to redirecting output from the relevant C functions sent to stdout?
I am not a C++ expert, but I think what I would like to do is provide a subclass of a C++ output stream buffer (ostream and ofstream?), which contains the same output that would otherwise get sent by the relevant C functions to stdout.
I would like the option of redirecting this data to a file stream or to standard output within the C++ application, if possible.
How might I do this? Can I leave my C code as-is and redirect stdout from within the C++ code?
EDIT
I can edit the C functions in question, so that a file pointer or descriptor is an argument. Would this help, being able to pass in where the output goes? What's unclear to me is how I would translate C++ IO and C IO. I can't pass in a C++ iostream to a C function, or can I?
In a comment I mentioned that C++ std::cout and C stdout are related in a tricky way, and that you can use stdout in C++ by including <cstdio>. I also gave the following link: http://gcc.gnu.org/onlinedocs/gcc-4.6.2/libstdc++/manual/manual/io_and_c.html
However, you might consider changing the API of your library, and provide functions which write to a user supplied stream, and/or to a user supplied file path.
On Linux, you might also use open_memstream or fopencookie
If I've understood your question correctly, no, at least with standard conforming code.
What could be related is std::ios_base::sync_with_stdio which ensures that IO made on some C++ streams are correctly synchronized with IO make of C streams. So stdout is synchronized with cout, stdin with cin and stderr width cerr. But that isn't designed to allow changing the streambuf in cout and have the change propagated to stdout (which is how I understood your request), and I'm far from sure on the intented effect if you do a freopen on stdout.
You need to set up a pipe, and run the C program as a stand-alone process with its stdout connected to the input end of the pipe. Your C++ program then needs to read from the output end of the pipe, and it will then get all the output from the C process.
UPDATE: I re-read the question a bit more after the downvotes and comments. I (now) realize the C code is running as a library, i.e. linked into the same executable as the C++ code.
I don't think you can forcibly redirect stdout for the C code without affecting the C++'s program's output stream at the same time, which seems like a very high price to pay in order to have a library.
I still think the solution is to "sandbox" the C code in a process of its own, with a redirected output that you can then read as desired. It would of course be better to re-write the C functionality to return results instead of printing them, but I assume that's not an option.
You say that the C code uses fprintf(), i.e. the variant with an explicit file handle, so perhaps you can use that and make it accept a FILE * from the outside, in which case you can feed it a pipe without having to subprocess it.
Very interested in seeing other answers, perhaps there's an approach I'm missing.
UPDATE 2: If you have the chance to control which FILE * you pass into the C library, then it's easy:
To have the output appear with the C++ program's ordinary output, just pass in stdout.
To capture the output to a file, fopen() the file and pass in the resulting FILE *.
If you want to do both at the same time, that's a bit more troublesome, again. In that case I would, again, recommend a pipe or socket so that the C++ side is responsible for reading out the output generated by the C library, and do what it wishes with it.

Calling external files (e.g. executables) in C++ in a cross-platform way

I know many have asked this question before, but as far as I can see, there's no clear answer that helps C++ beginners. So, here's my question (or request if you like),
Say I'm writing a C++ code using Xcode or any text editor, and I want to use some of the tools provided in another C++ program. For instance, an executable. So, how can I call that executable file in my code?
Also, can I exploit other functions/objects/classes provided in a C++ program and use them in my C++ code via this calling technique? Or is it just executables that I can call?
I hope someone could provide a clear answer that beginners can absorb.. :p
So, how can I call that executable file in my code?
The easiest way is to use system(). For example, if the executable is called tool, then:
system( "tool" );
However, there are a lot of caveats with this technique. This call just asks the operating system to do something, but each operating system can understand or answer the same command differently.
For example:
system( "pause" );
...will work in Windows, stopping the exectuion, but not in other operating systems. Also, the rules regarding spaces inside the path to the file are different. Finally, even the separator bar can be different ('\' for windows only).
And can I also exploit other functions/objects/classes... from a c++
and use them in my c++ code via this calling technique?
Not really. If you want to use clases or functions created by others, you will have to get the source code for them and compile them with your program. This is probably one of the easiest ways to do it, provided that source code is small enough.
Many times, people creates libraries, which are collections of useful classes and/or functions. If the library is distributed in binary form, then you'll need the dll file (or equivalent for other OS's), and a header file describing the classes and functions provided y the library. This is a rich source of frustration for C++ programmers, since even libraries created with different compilers in the same operating system are potentially incompatible. That's why many times libraries are distributed in source code form, with a list of instructions (a makefile or even worse) to obtain a binary version in a single file, and a header file, as described before.
This is because the C++ standard does not the low level stuff that happens inside a compiler. There are lots of implementation details that were freely left for compiler vendors to do as they wanted, possibly trying to achieve better performance. This unfortunately means that it is difficult to distribute a simple library.
You can call another program easily - this will start an entirely separate copy of the program. See the system() or exec() family of calls.
This is common in unix where there are lots of small programs which take an input stream of text, do something and write the output to the next program. Using these you could sort or search a set of data without having to write any more code.
On windows it's easy to start the default application for a file automatically, so you could write a pdf file and start the default app for viewing a PDF. What is harder on Windows is to control a separate giu program - unless the program has deliberately written to allow remote control (eg with com/ole on windows) then you can't control anything the user does in that program.

C/C++ Question about trace-programming techniques

I have the following question and from a systems perspective want to know how to achieve this easily and efficiently.
Given a task 'abc' that has been built with debug information and a global variable "TRACE" that is normally set to 0, I would like to print out to file 'log' the address of each function that is called between the time that TRACE is set to 1 and back again to 0.
I was considering doing this through a front-loading / boot-strapping task that I'd develop which looks at the instructions for a common pattern of jump/frame pointer push, writing down the address and then mapping addresses to function names from the symbolic debug information in abc. There could be better system level ways to do this without a front-loader though, and I'm not sure what is most feasible.
Any implemented techniques out there?
One possibility is to preprocess the source before compiling it. This preprocessing would add code at the beginning of each function that would check the TRACE global and, if set, write to the log. As Mystagogue said, the compiler has preprocessor macros that expand to the name of the function.
You might also look at some profiling tools. Some of them have functionality close to what you're asking for. For example, some will sample the entire callstack periodically, which can tell you a lot about the code flow without actually logging every call.
Looking for a common prologue/epilogue won't work in the presence of frame-pointer omission and tail call optimization. Also, modern optimizers like to split functions into several chunks and merge common tail chunks of different functions.
There is no standard solution.
For Microsoft compiler, check out _penter and _pexit hooks. For GCC, look at -finstrument-functions option and friends.
Also, on x86 Windows you can use a monitor such as WinApiOverride32. It's primarily intended for monitoring DLL and system API calls, but you can generate a description file from your application's map file and monitor internal functions as well.
(Edited: added link to GCC option.)
Make sure you've looked into the __func__ or __FUNCTION__ predefined identifiers. They provide a string literal of the function/method name you are currently executing.