我有一个 Dart 命令行程序,希望能够将数据从 shell 传输到 Dart 程序(例如,cat file.txt | dart my_program.dart或者接受输入,直到用户使用Ctrl+d)。通过在线教程,我找到的关于保存标准输入输入的唯一文档是stdin.readLineSync(). 然而,顾名思义,这只读取第一行。
如何将标准输入的全部内容捕获到字符串中?另外,如果用户尝试通过管道输入一个非常大的文件,是否会存在任何安全问题?字符串的长度有限制吗?我该如何防范?
感谢您的帮助!
如果以交互方式使用以下程序,它将回显您的输入,但将每个字符大写。
您还可以通过管道将文件传递给它。
dart upper_cat.dart < file.txt
Run Code Online (Sandbox Code Playgroud)
这将输出每个字符大写的文件。
dart upper_cat.dart < file.txt
Run Code Online (Sandbox Code Playgroud)
还有控制台库可以帮助处理此类事情。我还没有尝试过,但尝试一下并报告回来;)
以下示例处理 UTF8 输入 - 上面的示例需要 1 字节字符作为输入。
import 'dart:convert';
import 'dart:io';
main() {
// Stop your keystrokes being printed automatically.
stdin.echoMode = false;
// This will cause the stdin stream to provide the input as soon as it
// arrives, so in interactive mode this will be one key press at a time.
stdin.lineMode = false;
var subscription;
subscription = stdin.listen((List<int> data) {
// Ctrl-D in the terminal sends an ascii end of transmission character.
// http://www.asciitable.com/
if (data.contains(4)) {
// On my computer (linux) if you don't switch this back on the console
// will do wierd things.
stdin.echoMode = true;
// Stop listening.
subscription.cancel();
} else {
// Translate character codes into a string.
var s = LATIN1.decode(data);
// Capitalise the input and write it back to the screen.
stdout.write(s.toUpperCase());
}
});
}
Run Code Online (Sandbox Code Playgroud)
我研究了代码stdin.readLineSync()并能够修改它以满足我的需要:
import 'dart:convert';
import 'dart:io';
String readInputSync({Encoding encoding: SYSTEM_ENCODING}) {
final List input = [];
while (true) {
int byte = stdin.readByteSync();
if (byte < 0) {
if (input.isEmpty) return null;
break;
}
input.add(byte);
}
return encoding.decode(input);
}
void main() {
String input = readInputSync();
myFunction(input); // Take the input as an argument to a function
}
Run Code Online (Sandbox Code Playgroud)
我需要从标准输入同步读取,以便暂停程序,直到读取整个标准输入(直到文件末尾或Ctrl+ )。d
感谢你的帮助!我想如果没有你的帮助我就无法解决这个问题。
| 归档时间: |
|
| 查看次数: |
2375 次 |
| 最近记录: |