在Linux系统中,获取标准输入(Standard Input,通常缩写为stdin)是一个常见的操作,尤其是在编写Shell脚本或者使用命令行工具时。标准输入通常指的是键盘输入,但也可以来自文件或其他进程的输出。
read
命令:在Shell脚本中,可以使用read
命令从标准输入读取数据。#!/bin/bash
echo "请输入一些文本:"
read input
echo "你输入的是: $input"
echo "Hello World" | grep "Hello"
cat < filename.txt
#include <stdio.h>
int main() {
char buffer[256];
printf("请输入一些文本: ");
fgets(buffer, sizeof(buffer), stdin);
printf("你输入的是: %s", buffer);
return 0;
}
grep
, sed
, awk
等。#include <stdio.h>
#include <string.h>
#define MAX_INPUT_SIZE 100
int main() {
char input[MAX_INPUT_SIZE];
printf("请输入一些文本(最多 %d 个字符): ", MAX_INPUT_SIZE - 1);
if (fgets(input, sizeof(input), stdin) != NULL) {
// 移除换行符
input[strcspn(input, "
")] = 0;
if (strlen(input) == 0) {
printf("输入为空,请输入有效的文本。
");
} else {
printf("你输入的是: %s
", input);
}
} else {
printf("读取输入时发生错误。
");
}
return 0;
}
在这个示例中,程序限制了用户输入的最大长度,并且检查了输入是否为空,以及处理了读取输入时可能发生的错误。
领取专属 10元无门槛券
手把手带您无忧上云