First of all, I know there is a question with an identical name, however it deals with c++ and not c.
Is there any way to set a string to the clipboard in c?
This is the mentioned question if anyone is curious, even though it is for windows.
I need it to be in c because I am writing a program in c, and I would like to copy a 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 is saving 2 new lines in addition to the string. ARR_MAX is 300.
you tagged your question for osx. so this should be sufficient: 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 having to call non-native c. Whether this is directly possible I don`t know.
if you can accept some hacky behavior you could invoke the pbcopy command.
http://osxdaily.com/2007/03/05/manipulating-the-clipboard-from-the-command-line/
this would be very easy to implement. here is a short function which should copy to clipboard. But I dont have osx handy so cannot test 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With