Get highlighted text & open program with it (replicate clipboard.exe behavior) - c

Is it possible to highlight text with your cursor in any program, like you do with str+c and start a tool with the highlighted text as argument?
As far as I know, in Linux as well as in Windows, one can call a script/program with a custom shortcut. I assume str+c just does the same, calling a little program with the highlighted text as argument. How to replicate this?
For demonstration purposes, let's take this C - program printing the value it was called with:
#include <stdio.h>
int main(int argc, char**argv){
if(argc == 2){
printf("program called with: '%s'\n", argv[1]);
}
}
Can one type the text "HelloWorld" in Word for example, highlight it, and press something like str+alt+p, calling
someprogram.exe HelloWorld
or as for Linux
someprogram HelloWorld
I am really curious if this is possible.
Edit: I'm interested to know, how to replicate the clipboard.exe functionality. I have written a program "write_custom.exe" storing anything given as argument (argv[1]) in a text-file, after deleting it's previous content. Other programs can read the content of this text-file and so are able to use this custom clipboard. It's purpose is mainly for self-teaching.
As I am at the beginning of my codeing career, I only know C, but I am open for solutions in other languages as well. My goal is to run this write_custom.exe, with highlighted text as argument, on my computer and my Linux-VM.

You might want to check out ncurses (Linux) and Console API (Windows). The code will not be cross-platform, but you can pretty easily write some code to make them share some basic behavior :).

Related

C/C++ BEGINNER - fgets with stdin causing unexpected 'loop' results

I'm a programming student who's only really looked at Java up until now. This semester is our first time using C and I'm having a lot of trouble wrapping my head around some of the simplest functions. I really have no idea what I'm doing. I couldn't even get Eclipse to work correctly with MinGW so I eventually gave up and reverted to Netbeans.
So basically I'm trying to use fgets to read user input for a switch-case menu, but I can't get fgets to work in even the simplest situations. To troubleshoot I tried copying a simple fgets example from online, but even that is giving me unexpected results.
When I run the code below it just runs an infinite empty loop (it does not prompt for user entry at all, it does not accept any user entry, it just 'runs' forever and the console remains blank). When I delete the fgets line and remove the other reference to the 'name' variable it works as you would expect (prints the user entry prompt and then ends).
Example code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char name[10];
printf("Who are you? ");
fgets(name,10,stdin);
printf("Glad to meet you, %s.\n",name);
return(0);
return (EXIT_SUCCESS);
}
Any advice would be appreciated!
Other info:
I am running - Win 8 (poor me) & Netbeans IDE 8.0 (with MinGW)
When creating my C project I select File=> New Project=> C/C++=> C/C++ Application
EDIT: When I run the program I have tried:
1) right clicking the project file => Run; and
2) clicking the big green arrow in the netbeans ribbon;
.... neither works.
This code should work, but for you to be able to input anything, you need to run in in a proper terminal.
My guess is that you're running it inside your IDE and it's set to use pipes as stdin/stdout. Instead you should start cmd.exe and run the program in there (you'll have to navigate to the correct directory first).
Or, optionally, there might be a setting in your IDE to run the program using cmd.exe or with a builtin terminal.
A final note. You should learn to use sizeof whenever a buffer size is required. I.e. change this:
fgets(name,10,stdin);
to
fgets(name, sizeof(name), stdin);
Also, please use spaces to make your code more readable. Reading code is a big part of programming.
1) You might want to flush the file, after printf("Who are you? "); with fflush(stdout);
2) You have two return statements (which is harmless).
Other than that, your code is fine.
It works perfect - but you might want using fflush(stdin); before the fgets() call.
Also remember fgets return a string with '\n' after a user input - solved simply with name[strlen(name)-1]='\0'; - which is basically putting NULL as an "end of a string" symbol, basically you remove the '\n'.
And DO NOT change 10 to sizeof(name) - it doesn't matter at all, basically it's even supposedly worse as you can't use this in functions properly (sizeof(name) won't always match the length and would be the size of the pointer).
You should try compiling with MinGW if it didn't work, it will surely work on it.
A reminder: fgets() may let you enter MILLION characters, but it will take the first 10, in this case, at least.

Simple C Wrapper Around OpenSSH (with Cygwin on Windows)

I am packaging a program on Windows that expects to be able to externally call OpenSSH. So, I need to package ssh.exe with it and I need to force ssh.exe to always be called with a custom command line parameter (specifically -F to specify a config file it should use). There is no way to force the calling program to do this, and there are no simple ways to do this otherwise in Windows (that I can think of anyway - symlinks or cmd scripts won't work) so I was just going to write a simple wrapper in C to do it.
This is the code I put together:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int ret;
char **newv = malloc((argc + 2) * sizeof(*newv));
memmove(newv, argv, sizeof(*newv) * argc);
newv[argc] = "-F ssh.conf";
newv[argc+1] = 0;
ret = execv("ssh.orig.exe", newv);
printf("execv failed with return value of %i", ret);
return ret;
}
I then compile this code using GCC 4.6.3 in Cygwin and it runs without error; however, there is a strange behavior with regards to input and output. When you go to type at the console (confirming the authenticity of the host and entering in a password, etc) only part of the input appears on the console. For example, if I type in the word 'yes' and press enter, only the 'e' will appear on the console and SSH will display an error about needing to type 'yes' or 'no'. Doing this from the Windows command prompt will result in your input going back to the command propmt, so when you type 'yes' and press enter, you get the ''yes' is not recognized as an internal or external command...' message as if the input were being typed at the command prompt. Eventually SSH will time out after that.
So, I'm obviously missing something here, and I'm assuming it has something to do with the way execv works (at least the POSIX Cygwin version of it).
Is there something I'm missing here or are there any alternatives? I was wondering if maybe I need to fork it and redirect the I/O to the fork (although fork() doesn't seem to work - but there are other issues there on Windows). I tried using _execv from process.h but I was having issues getting the code right for that (also could have been related to trying to use gcc).
It's also possible that there may be a non-programming way to do this that I haven't thought of, but all of the possibilities I've tried don't seem to work.
Thoughts?
I ended up finding a solution to this problem. I'm sure there were other ways to do this, but this seems to fix the issue and works well. I've replaced the execv line with the following code:
ret = spawnv(P_WAIT, "ssh.orig.exe", newv);
You have to use 'P_WAIT' otherwise the parent process completes and exits and you still have the same problem as before. This causes the parent process to wait, but still transfers input and output to the child process.

c console application auto-complete dynamic arguments

I am looking for a method of having console auto complete - such that given an application like:
int main (int argc, char ** argv)
{
if (argc == 1) return EXIT_FAILURE;
if (strcmp(argv[1], "good")==0) printf("good\n");
if (strcmp(argv[1], "bad")==0) printf("bad\n");
return EXIT_FAILURE;
}
When running it, I would like pressing [tab] after the command, such that it would give me one of the possible useful options.
Example:
./a.out g[tab]
would auto complete to
./a.out good
I don't want to edit /etc/bash-completion.d/, I was hoping for a much stronger auto-complete, something like a function in the executable itself that would be called - perhaps so it could query a database for the list of possible options. Or perhaps output a message letting you know what the options are.
If you think this is simply totally impossible, let me know!
Completions are a property of the shell you run the application from. You will have to provide completion functions for all the shells you want to support (bash, zsh, tcsh and fish have customizable completions). A completion function can call your application (e.g. run you_application --list-possible-arguments) or do whatever it chooses to generate the completions — it's already a “strong” completion in your terminology.
In bash, you declare completions with the complete built-in. Look in /etc/completion.d for examples (gpg is a fairly simple example; git is a rather involved one).
If you are using BASH then have a look at this similar post:
Auto-complete command line arguments
================================
If you want to provide your own command line then have a look at the Readline library:
The GNU Readline library provides a
set of functions for use by
applications that allow users to edit
command lines as they are typed in.
Both Emacs and vi editing modes are
available. The Readline library
includes additional functions to
maintain a list of previously-entered
command lines, to recall and perhaps
reedit those lines, and perform
csh-like history expansion on previous
commands.

Using popen() to open a program in command line?

Is it possible to open a program using another program? For example:
I want to make a command line application in C that will prompt the user to type in the name of a program (lets say Microsoft Word.app), and that program will launch. Would I do something like this:
#include <stdio.h>
#include <time.h>
int main (int argc, const char * argv[]) {
char programName[1000];
printf("Type in the name of the program you would like to open: ");
scanf("%s", programName);
popen(programName);
}
However, popen() asks me for another char. How would I go about using popen() to open the program?
EDIT: The following code works!
#include <stdio.h>
#include <time.h>
int main (int argc, const char * argv[]) {
char programName[1000];
char app[100] = ".app";
char openApp[100] = "open /Applications/";
printf("Type in the name of the program you would like to open: ");
scanf("%s", programName);
strcat(openApp, programName);
strcat(openApp, app);
system(openApp);
}
popen lets you launch a program and get a file descriptor to its input or output, much like fopen works for files. For instance, if you wanted to read the output of your program, you'd use popen("program", "r"). On the other hand, if you want to write to its input, you would use popen("program", "w"). Mac OS X also allows for r+, which lets you read the output and write to the input but this capability isn't standard and shouldn't be relied on for cross-platform code.
If you just want to launch a program, you might as well use the system function, which does that and waits until the program exits, at which point it returns the status code. system actually invokes the shell to work, so arguments will undergo expansion (environment variables, ~, etc).
EDIT Following your comment that system("Microsoft Word.app") doesn't work as you'd expect: there are several reasons for this, actually. Starting with the message you get: this is because what you wrote is equivalent to opening a terminal window and typing Microsoft Word.app. In other words, it tries to find a program called "Microsoft", then pass it the argument "Word.app". You would need to either quote the program name or escape spaces to have the shell understand it's a whole program name and not a program name then an argument: system("Microsoft\ Word.app")
Now, this should complain saying that the shell can't find the program "Microsoft Word.app", which is already a step forward.
This is because on Mac OS, app files aren't executable files: they're folders that the Finder displays as a single file. You can verify that by ctrl+clicking (or right-clicking) an app and selecting "Show package contents" (this will open the app folder). The actual executable for Microsoft Word.app must be somewhere along the path of Microsoft Word.app/Contents/MacOS/Microsoft Word.
As you can see, this is getting kind of complex. Luckily enough, Apple provides the open executable, which can use a bunch of OS services to figure out those details. It allows to launch applications in the following fashion:
open -a Microsoft\ Word
This should launch Word. (Notice how you still need to escape the spaces.) In pure C code, that would get you something like this:
system("open -a Microsoft\\ Word");
If you choose to use Objective-C and Cocoa, however, there is a very simple way to open applications:
NSString* appName = #"Microsoft Word"; // no escape!
[[NSWorkspace sharedWorkspace] launchApplication:appName];
NSString objects can be created from C string easily enough:
NSString* appName = [[NSString alloc] initWithCString:programName encoding:NSUTF8StringEncoding];
[[NSWorkspace sharedWorkspace] launchApplication:appName];
[appName release];
It would be better to use system(3) for this purpose.
The popen(3) function establishes a pipeline that can be read or written by the caller. But GUI applications do not use standard input and standard output, they connect to the graphical interface server, sometimes called the "window server". This server is already running and already has decided what its keyboard input will be, and it is always writing its output to the video device.
To start a .app you should actually run the open(1) program, so try something like:
system("open /Applications/MacVim.app");

How can I see an the output of my C programs using Dev-C++?

I'm looking to follow along with The C Programming Language (Second Addition) on a machine running Vista.
So far, I've found Dev-C++ the easiest IDE to do this in. However, I still have one problem. Whenever I run my compiled code, for example: a simple hello world program, it runs, but the console window just flickers on the screen, and I can't see the output.
How can I see an the output of my C programs using Dev-C++? I found a C++ specific solution, System("pause"), and a really ugly C solution, while looping fflush(stdout), but nothing nice and pretty.
I put a getchar() at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar, getch, or getc
In Windows when a process terminates, the OS closes the associated window. This happens with all programs (and is generally desirable behaviour), but people never cease to be surprised when it happens to the ones they write themselves.
I am being slightly harsh perhaps; many IDE's execute the user's process in a shell as a child process, so that it does not own the window so it won't close when the process terminates. Although this would be trivial, Dev-C++ does not do that.
Be aware that when Dev-C++ was popular, this question appeard at least twice a day on Dev-C++'s own forum on Sourceforge. For that reason the forum has a "Read First" thread that provides a suggested solution amongst solutions to many other common problems. You should read it here.
Note that Dev-C++ is somewhat old and no longer actively maintained. It suffers most significantly from an almost unusable and very limited debugger integration. Traffic on the Dev-C++ forum has been dropping off since the release of VC++ 2005 Express, and is now down to a two or three posts a week rather than the 10 or so a day it had in 2005. All this suggest that you should consider an alternative tool IMO.
Use #include conio.h
Then add getch(); before return 0;
The easiest thing to do is to run your program directly instead of through the IDE. Open a command prompt (Start->Run->Cmd.exe->Enter), cd to the folder where your project is, and run the program from there. That way, when the program exits, the prompt window sticks around and you can read all of the output.
Alternatively, you can also re-direct standard output to a file, but that's probably not what you are going for here.
For Dev-C++, the bits you need to add are:-
At the Beginning
#include <stdlib.h>
And at the point you want it to stop - i.e. before at the end of the program, but before the final }
system("PAUSE");
It will then ask you to "Press any key to continue..."
Add this to your header file #include
and then in the end add this line : getch();
You can open a command prompt (Start -> Run -> cmd, use the cd command to change directories) and call your program from there, or add a getchar() call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause"), which will display a "Press enter to continue..." (or something like that) message.
Add a line getchar(); or system("pause"); before your return 0; in main function.
It will work for you.
;
It works...
#include <iostream>
using namespace std;
int main ()
{
int x,y; // (Or whatever variable you want you can)
your required process syntax type here then;
cout << result
(or your required output result statement); use without space in getchar and other syntax.
getchar();
}
Now you can save your file with .cpp extension and use ctrl + f 9 to compile and then use ctrl + f 10 to execute the program.
It will show you the output window and it will not vanish with a second Until you click enter to close the output window.
i think you should link your project in console mode
just press Ctrl+h and in General tab select console.
When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.
The use of line system("PAUSE") will fix that problem and also include the pre processor directory #include<stdlib.h>.
Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
a=5;b=6;
c=a*b;
printf("%d",c);
system("PAUSE");
return 0;
}
Hope this helped.

Resources