標籤:style http color io os 使用 ar for 資料
本文中使用的管道,是Linux中把前一個程式的輸出放到後一個程式的輸入的‘|‘符號,並不是自己實現的管道
代碼1:程式a.c輸出“HelloWorld”,並由b.c通過管道接住輸出
a.c代碼
#include <stdio.h>void main(){ printf("Hello World! :-P\n");}
b.c代碼
#include <stdio.h>void main(){ char input[100]; char ch; int i = 0; while(ch = getchar()) { if (ch != ‘\n‘) { input[i++] = ch; } else { input[i] = ‘\0‘; break; } } printf(":-) %s\n", input);}
編譯和運行,輸入命令:
gcc a.c -o agcc b.c -o b./a | ./b
運行效果
代碼2:程式a.c以參數的形式輸入顏色,傳給b.c,輸出指定顏色的"Hello World!"
a.c代碼
#include <stdio.h>#include <stdlib.h>void main(int argc, char *argv[]){ //輸出main函數接收到的參數 int i; for (i = 1; i < argc; i++) { printf("%s\n", argv[i]); } printf("end\n"); exit(EXIT_SUCCESS);}
b.c代碼
#include <stdio.h>#include <stdlib.h>#include <string.h>void main(){ char s[20]; while (1) { scanf("%s", s); if (strcmp(s, "black") == 0) { printf("\e[30;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "red") == 0) { printf("\e[31;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "green") == 0) { printf("\e[32;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "yellow") == 0) { printf("\e[33;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "blue") == 0) { printf("\e[34;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "purple") == 0) { printf("\e[35;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "darkgreen") == 0) { printf("\e[36;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "white") == 0) { printf("\e[37;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "end") != 0) { printf("Hello World! (UNKNOWN COLOR)\n"); } else { printf("END!\n"); break; } } exit(EXIT_SUCCESS);}
編譯和運行,輸入命令:
gcc a.c -o agcc b.c -o b./a 參數 | ./b
運行效果
END
Linux下的C程式,通過最簡單的管道(‘|‘)實現兩個程式間的資料傳遞