2014-11-20 87 views
3

首先,我知道有一个问题具有相同的名称,但它处理C++而不是c。将字符串复制到剪贴板c

有没有什么办法可以将字符串设置为c中的剪贴板?

This is the mentioned question if anyone is curious, even though it is for windows.

我需要它在C,因为我用C写一个程序,我想一个字符串复制到剪贴板。

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 

上面的代码除了字符串以外还保存了2个新行。 ARR_MAX是300.

+0

您链接到的问题是为Windows。你已经为OS X标记了你的问题。当然,这些完全不同。请澄清你的问题。另外,你能解释一下为什么**使用C语言很重要? – 2014-11-20 23:34:31

+0

我已经添加了一个简短的功能,它正是你想要的。而不使用strncat,这似乎对我来说很迟钝。 – 2014-11-22 05:19:19

+0

尝试接受一个提示! – 2014-12-02 05:01:19

回答

0

您为osx标记了您的问题。所以这应该是足够的: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PasteboardGuide106/Articles/pbCopying.html#//apple_ref/doc/uid/TP40008102-SW1

但是有问题必须调用非本地c。这是否是直接可能的,我不知道。

如果你可以接受一些hacky行为,你可以调用pbcopy命令。

http://osxdaily.com/2007/03/05/manipulating-the-clipboard-from-the-command-line/

,这将是很容易实现。这里是一个应该复制到剪贴板的简短功能。但我没有OSX方便,所以不能测试自己

#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); 
} 
+1

谢谢,这不是目标吗? – user1753491 2014-11-20 23:24:23

+0

是的。我没有目标c的经验,所以不能给你提供更多的帮助,你将如何与c一起使用它。但我认为它是c的一个超集,所以如果你幸运的话,它可能非常简单。 – 2014-11-20 23:25:37

+2

所以你的答案归结为:使用objective-c来代替,这里是官方文档的链接... – Deduplicator 2014-11-20 23:27:06