在C语言中将字符串复制到剪贴板

6

首先,我知道有一个同名的问题,但它涉及c++而不是c。

有没有办法在c中将字符串设置到剪贴板中?

这是提到的问题,如果有人感兴趣,尽管它是为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。

你链接的问题是针对Windows的。而你标记了OS X的问题。这两者当然完全不同。请澄清你的问题。另外,你能解释一下为什么使用C语言很重要吗? - Ken Thomases
1
我已添加了一个短函数,它完全符合你的要求,而且没有使用对我来说看起来很愚蠢的strncat函数。 - rowan.G
1个回答

2
您将您的问题标记为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
谢谢,那不是Objective-C吗? - user1753491
2
所以你的答案归结为:使用Objective-C,这里是官方文档链接... - Deduplicator
并不是所有语言都以某种方式支持与C的接口。 - rowan.G
以前有一个Carbon Pasteboard Manager,它是用C语言编写的,但在10.5版本中消失了。您可以使用Objective-C运行时API获取NSPasteboard指针,该API也是用C语言编写的,但至少需要ObjC运行时才能使函数正常工作。现在随OS X一起提供的pbcopy版本链接到Cocoa,因此Apple也在使用ObjC。使用Swift吧! - iluvcapra
我对整个苹果开发环境没有经验。或许你比我更能回答他的问题? - rowan.G
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接