Copy line to clipboard in c
First of all, I know there is a question with an identical name, however, it deals with C ++, not c.
Is there a way to set a string to the clipboard in c?
This is the mentioned question in case anyone is interested, although this is for windows.
I need it to be in c because I am writing a program in c and I would like to copy the string to the clipboard.
printf("Welcome! Please enter a sentence to begin.\n> ");
fgets(sentence, ARR_MAX, stdin);
//scan in sentence
int i;
char command[ARR_MAX + 25] = {0};
strncat(command, "echo '",6);
strncat(command, sentence, strlen(sentence));
strncat(command, "' | pbcopy",11);
command[ARR_MAX + 24] = '\0';
i = system(command); // Executes echo 'string' | pbcopy
The above code stores two more lines in addition to the line. ARR_MAX - 300.
source to share
you tagged your question for osx. so this should be enough: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PasteboardGuide106/Articles/pbCopying.html#//apple_ref/doc/uid/TP40008102-SW1
however, there is the problem of calling non-native c. Whether this is possible directly, I do not know.
if you can accept some kind of hacky behavior you can call the pbcopy command.
http://osxdaily.com/2007/03/05/manipulating-the-clipboard-from-the-command-line/
it would be very easy to implement. here is a short function that should be copied to the clipboard. But I don't have osx so I can't check myself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int copytoclipboard(const char *str) {
const char proto_cmd[] = "echo '%s' | pbcopy";
char cmd[strlen(str) + strlen(proto_cmd) - 1]; // -2 to remove the length of %s in proto cmd and + 1 for null terminator = -1
sprintf(cmd ,proto_cmd, str);
return system(cmd);
}
int main()
{
copytoclipboard("copy this to clipboard");
exit(0);
}
source to share