2014-11-20 71 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