clear screen in Fortran - windows

I've been searching for a considerably long time for this. Does anyone know how to clear the screen in a console app in Fortran language?
any help will be very much appretiated!

Fortran, qua Fortran, knows nothing of such concepts as screens or keyboards or, for that matter, computers. There is, therefore, no language-standard way of clearing a screen from Fortran. You will have to find some platform-dependent approach.
Most Fortran compilers have some way of doing this, for example Intel Fortran provides the SYSTEM function.

Contrary to others I would not call SYSTEM() (standard Fortran 2008 alternative is execute_command_line()) but I would print right ANSI escape code http://en.wikipedia.org/wiki/ANSI_escape_code:
print *, achar(27)//"[2J"
This will be much faster than calling SYSTEM().
This works in typical Linux terminals, but will not work in the MS Windows terminal.
Another more practical reference how to use the escape code is http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html

In Fortran 90/95 your best option is the system command which is a vendor supplied extension (i.e., not part of the F90/95 standard so some obscure Fortran compilers may not have it but all major ones do).
$ cat clear.f90
program
call system('clear')
end
$ gfortran clear.f90 -o clear
$ ./clear

It depends on your specific sytem and compiler. There is no general way. Fortran doesn't know about specific hardware devices like terminal screens and printers. (Neither do most other languages). The details depend entirely on your specific system.
My advice would be to clear the terminal by invoking the relevent script via the command line - but this is not nice. it is generally more portable to write the output to an ordinary text file and then execute appropriate system commands to print that file to screen. This way you can manipulate the file as you wish...
See here for a simalar question from which these some of the above text was salvaged.

In Fortran ACHAR(N) returns the ASCII of N, so my preferred method would be:
WRITE(*,'(2f15.9,A5)',advance='no') float1,float2,ACHAR(13)
ACHAR(13) returns carriage return character \r in Python. So after printing, it returns the cursor to the beginning of the line where it can be overwritten.
After you are out of the loop you can use CALL SYSTEM('clear') to clean the screen.
This is helpful since CALL SYSTEM('clear') is slower and uses a lot of CPU, you can check this by replacing the above method with
WRITE(*,'(2f15.9)',advance='no') float1,float2;CALL SYSTEM('clear')
and check the difference in time taken in loops.

This Works For Me in FTN95
program
call system('CLS')
end

I found yet another way to clear screen in UNIX like systems by printing the output of clear command (from manual of clear command which states you can write the output to a file and then cat it to clear the screen)
So better way is to clear > temp.txt and use the characters in files in a print statement
Although both do the same thing, calling SYSTEM("foo") is very very (100+ times) slower than directly printing those characters
For example:
program clear
implicit none
INTEGER::i
do i = 1, 1000
print *, "Test"
call system("clear")
enddo
end program clear
This program takes anywhere between 3.1 to 3.4 seconds.
But instead of calling system, if I directly print the characters like this :
program clear
implicit none
INTEGER::i
do i = 1, 1000
print *, "Test"
print *, "[H[2J[3J"
enddo
end program clear
This produces the exact same result but takes anywhere between 0.008 to 0.012 seconds (8 to 12 ms)
In fact, running the second loop 100,000 is faster than CALL SYSTEM("clear") 1000 times
EDIT: Don't copy-paste from here, it won't work, (characters are replaced on StackOverflow)
Just use clear > file and copy the contents of the file into a print statement
Screenshot of actual code(from preview):
These characters aren't supported I guess, They disappear in the answers (They work fine in preview)

Related

Is it possible to capture the bitstream of post-interpreted code? (pre-execution) eg. speedup calls I make often

I've wondered this many times and in many cases, and I like to learn so general or close-but-more needed answers are acceptable to me.
I'll get specific, to help explain the question. Please remember that this question is more about accelerating common interpreted language calls (yes, exactly the same arguments), than it is about the specific programs I'm calling in this case.
Here we go:
Using i3WM I use i3lock-fancy to lock my workspace with a key-combo mapped to the command:
i3lock-fancy -p -f /usr/share/fonts/fantasque_mono.ttf
So here is why I think this is possible, though my google-fu has failed me:
i3lock-fancy is a bash script, and bash is an interpreted language
each time I run the command I call it with the same arguments
Theoretically the interpreter is spitting out the same bitstream to be executed, right?
Please don't complain about portability, I understand it, the captured bitstream, would not be
For visual people:
When I call the above command > bash interpreter converts bash-code to byte-code > CPU executes byte-code
I want to:
execute command > bash interpreter converts to byte-code > save to file
so that I can effectively skip interpretation (since it's EXACTLY the same every time):
call file > CPU executes byte-code
What I tried:
Looking around on SO before asking the question lead me shc which is similar in some ways to what I'm asking for.
But this is not what shc is for (thanks #stefan)
is there a way to do this which is more like what I've described?
Simply put, is there a way to interpret bash, and save the result without actually running it?

Using standard io stream:stdin and stdout in a matlab exe

Question
I want it to 'listen' to the standard input stream in a running (compiled) Matlab executable.
This is how I believe it is done in c or a similar language:
#include stdio.h
fgets(line, 256, stdin)
Or more elaborately, it it can be used as such:
if (!fgets(line, 256, stdin))
return;
if (line[0] == '\n')
continue;
sscanf(line, "%s", command);
Answer
For completeness I will leave the background and notes intact, but with the help of Amro and EitanT I have managed to work it out.
Background
I have found how to do this in other languages, and here are some instructions for the compilation process.
However, I have not found anywhere how to 'listen' to the input in Matlab.
The closest I have come is this description of C-like IO in Octave, but I cannot make progress with this as I looking for a solution in MATLAB.
Note that altering or wrapping the program that sends the data over the stream is not possible, and that I would prefer a pure MATLAB solution rather than wrapping my entire program. If I were to call a trivial function from MATLAB in a different language that would be ok.
What have I tried?
I tried a few functions from the command window like fgets(0) (fid = 0 seems to be the id corresponding to stdin (as mentioned by #EitanT and seen when trying fopen(0)) )but it just returns:
Operation is not implemented for requested file identifier.
I have also considered using the option in MATLAB to invoke system commands or execute java / perl commands, but so far without luck. I am also not sure whether these would still work after compilation.
Furthermore I attempted to use input('prompt','s') this works when I open the program via cmd, but does not do anything until I hit enter. (Which the program that I listen to of course will never do, in the best case I can get \n at the end of each line).
I also tried out waitinput from File Exchange but I think this is a dead end as it did not catch anything and seems to perform quite poorly.
Notes
I am using Windows 7 and MATLAB 2012b.
I found popen on File Exchange but that does not seem to be available for Windows.
When I simply type something like 'show me' this is properly sent to the standard output stream.
Let me illustrate with a toy example. Consider the following MATLAB function:
greet.m
function greet()
str = input('Enter your name: ','s');
fprintf('Hello %s\n',str)
end
Now lets compile it into a standalone application. Note that if you use the deploytool tool, make sure to choose "Console application" NOT "Windows standalone application" as target. The latter apparently produces an executable where the standard input is connected to the system shell not the MATLAB command prompt..
If you prefer to directly compile it yourself, use the following invocation:
mcc -o hello -W main:hello -T link:exe -N -v greet.m
(For reference, the "Windows app" target issues -W WinMain:hello instead)
Running the executable produces:
C:\> hello
Enter your name: Amro
Hello Amro
where the input from the keyboard is correctly handled.
It turns out that input reads the standard input stream.
The reason why I failed to collect my inputs, is because I was using it as follows:
input('prompt','s')
As a result the string 'prompt' was sent to the program calling my application, and as it considered this an invalid response/request it did not send anything.
I have succeeded in making a small test program, and unlike I suspected before it is NOT a problem that the other application doesn't hit enter after sending a command.
The general solution
This is the way I have my current setup,
while 1
stdin = input('','s'); % Note the empty first argument
if ~isempty(stdin)
stdout = process_input(stdin);
stdout % Displaying the result (And thus sending it to stdout)
end
end

Debugging a program without source code (Unix / GDB)

This is homework. Tips only, no exact answers please.
I have a compiled program (no source code) that takes in command line arguments. There is a correct sequence of a given number of command line arguments that will make the program print out "Success." Given the wrong arguments it will print out "Failure."
One thing that is confusing me is that the instructions mention two system tools (doesn't name them) which will help in figuring out the correct arguments. The only tool I'm familiar with (unless I'm overlooking something) is GDB so I believe I am missing a critical component of this challenge.
The challenge is to figure out the correct arguments. So far I've run the program in GDB and set a breakpoint at main but I really don't know where to go from there. Any pro tips?
Are you sure you have to debug it? It would be easier to disassemble it. When you disassemble it look for cmp
There exists not only tools to decompile X86 binaries to Assembler code listings, but also some which attempt to show a more high level or readable listing. Try googling and see what you find. I'd be specific, but then, that would be counterproductive if your job is to learn some reverse engineering skills.
It is possible that the code is something like this: If Arg(1)='FOO' then print "Success". So you might not need to disassemble at all. Instead you only might need to find a tool which dumps out all strings in the executable that look like sequences of ASCII characters. If the sequence you are supposed to input is not in the set of characters easily input from the keyboard, there exist many utilities that will do this. If the program has been very carefully constructed, the author won't have left "FOO" if that was the "password" in plain sight, but will have tried to obscure it somewhat.
Personally I would start with an ltrace of the program with any arbitrary set of arguments. I'd then use the strings command and guess from that what some of the hidden argument literals might be. (Let's assume, for the moment, that the professor hasn't encrypted or obfuscated the strings and that they appear in the binary as literals). Then try again with one or two (or the requisite number, if number).
If you're lucky the program was compiled and provided to you without running strip. In that case you might have the symbol table to help. Then you could try single stepping through the program (read the gdb manuals). It might be tedious but there are ways to set a breakpoint and tell the debugger to run through some function call (such as any from the standard libraries) and stop upon return. Doing this repeatedly (identify where it's calling into standard or external libraries, set a breakpoint for the next instruction after the return, let gdb run the process through the call, and then inspect what the code is doing besides that.
Coupled with the ltrace it should be fairly easy to see the sequencing of the strcmp() (or similar) calls. As you see the string against which your input is being compared you can break out of the whole process and re-invoke the gdb and the program with that one argument, trace through 'til the next one and so on. Or you might learn some more advanced gdb tricks and actually modify your argument vector and restart main() from scratch.
It actually sounds like fun and I might have my wife whip up a simple binary for me to try this on. It might also create a little program to generate binaries of this sort. I'm thinking of a little #INCLUDE in the sources which provides the "passphrase" of arguments, and a make file that selects three to five words from /usr/dict/words, generates that #INCLUDE file from a template, then compiles the binary using that sequence.

Benchmarking under Windows

Under most Unix-like systems, you can use the "time" command to execute a program and tell you how much space and time it used. Does anybody know of anything comparable for Windows?
(No, I don't particularly want to spend 6 months learning the Win32 API just for this...)
From the command line (low resolution, possibly inaccurate): echo %date% %time%
Programmatically: QueryPerformanceCounter. http://msdn.microsoft.com/en-us/library/ms644904(v=vs.85).aspx
If you want something of the order of millisecond accuracy (which is comparable to what the linux/unix time would give you) then timeGetTime() is what you need. It returns the number of milliseconds since the system was booted. include mmsystem.h and link against winmm.lib. However, all this would just give you a time value, you'd either need to put in a system() call in between or do something like dump the start time out to a file when called for the first time, and then read it the second time.
More pragmatic solutions, which may be more useful depending on your circumstances:
Write a batch script to call the program you wish you benchmark and wrap it so that it writes to a file:
echo "start" >> log.txt
do_my_stuff.exe
echo "stop" >> log.txt
and then use a tool as the excellent LogExpert to look at the timestamps
Install the cygwin tools and use the time that comes with that. If you only need to do this on your own machine, and the benchmark program doesn't require complex setting up (command line parameters, environment variables, etc) then this may be the easiest approach.
I use the 'time' utility in windows too. It comes with mingw+msys.

Why is this Perl require line taking so much time?

I have a Perl script that runs via a system() command from C. On a specific site (SunOS 5.10), when that script is run, it nearly always takes 6 seconds or more. On other sites, it runs pretty much instantly (0.1s). If I run the script manually, i.e. not from the C code, it also runs instantly. I eventually tracked the slowness down (by spitting out the time a whole bunch in a lot of different places), to a single require line. The file that it is requiring is another Perl script we wrote. The script consists of a single require (this file here), 3 scalars that are assigned integer values, and a handful of time/date conversion routines. The file ends with a 1;. That single require appears to take as much as 6 seconds on occasion, but as I said, not always even on the same machine. I'm absolutely stumped here. My only last thought is to turn on profiling, but the site doesn't have Devel::Profiler and my only other option (that I know of) would be to add it to the Perl command which would require me altering and recompiling the C code (doable but non-trivial).
Anybody have ANY idea what could be going on here? I don't think I can/want to put the entire date.pl that is being required, but it's pretty much exactly as I described; I could answer any questions about it that you have.
Thanks in advance.
You might be interested in A Timely Start by Jean-Louis Leroy. He had a similar problem and tracked it down to a long and deep module search path where perl usually found the modules in the last entries in #INC.
Six seconds is a long time. Have you checked what your network is doing during this?
My first thought was that spawning the new process when using the system() command could be the problem, but six seconds is too long.
I don't know much about perl, but I could imagine that for any reason, the access of the time module could invoke a call to a network time server. Just to get synchronized. Maybe this takes so long or maybe it is getting a time out.
It could be that this only happens for a newly spawned process -- hence only when you use the system() command.
just wild guessing...
So, this does nothing to answer your question directly, but please tell me that you're not actually running on perl 4? Assuming you're on perl 5, you could remove the entire file and replace the require with use POSIX qw(ctime) to get the version that comes with Perl.
If you do have to support perl4, I'll merely grumble something about version 5 being fifteen years old now and go away. :)

Resources