首先,我知道有一个同名的问题,但它涉及 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
Run Code Online (Sandbox Code Playgroud)
除了字符串之外,上面的代码还保存了 2 个新行。ARR_MAX 为 300。
您将您的问题标记为 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/manipulate-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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2299 次 |
| 最近记录: |