[英]Powershell's pipe to program using scanf
Recently I moved from Windows' cmd.exe to PowerShell. 最近,我从Windows的cmd.exe移到了PowerShell。 Later on I discovered that Microsoft decided to abandon standard stdin redirection method abc.exe < input.txt
and recommends using Get-Content input.txt | .\\abc.exe
后来我发现Microsoft决定放弃标准的stdin重定向方法abc.exe < input.txt
并建议使用Get-Content input.txt | .\\abc.exe
Get-Content input.txt | .\\abc.exe
. Get-Content input.txt | .\\abc.exe
。
Unfortunately new method crashed my app. 不幸的是,新方法使我的应用程序崩溃了。 I created this simple program to find the source of the problem 我创建了这个简单的程序来查找问题的根源
#include <cstdio>
int main() {
int x = -1;
scanf("%d", &x);
printf("%d", x);
return 0;
}
and discovered that this test program returns -1 instead of number inside input.txt. 并发现此测试程序返回-1而不是input.txt中的数字。
I also tested commands like echo 1 | .\\abc.exe
我还测试了命令echo 1 | .\\abc.exe
echo 1 | .\\abc.exe
and type input.txt | .\\abc.exe
echo 1 | .\\abc.exe
并type input.txt | .\\abc.exe
type input.txt | .\\abc.exe
and all of them print -1 to stdout. type input.txt | .\\abc.exe
,所有文件都将-1打印到stdout。
I would be grateful for any help. 我将不胜感激。
Edit 1: 编辑1:
Result of $OutputEncoding command: $ OutputEncoding命令的结果:
IsSingleByte : True
BodyName : us-ascii
EncodingName : US-ASCII
HeaderName : us-ascii
WebName : us-ascii
WindowsCodePage : 1252
IsBrowserDisplay : False
IsBrowserSave : False
IsMailNewsDisplay : True
IsMailNewsSave : True
EncoderFallback : System.Text.EncoderReplacementFallback
DecoderFallback : System.Text.DecoderReplacementFallback
IsReadOnly : True
CodePage : 20127
Edit 2: 编辑2:
I created this simple program to see what is piped to program: 我创建了这个简单程序,以查看通过管道传递给程序的内容:
#include <cstdio>
int main() {
char l;
while(scanf("%c", &l)) {
printf("%d\n", l);
}
return 0;
}
After running Get-Content input.txt | .\\abc.exe
运行Get-Content input.txt | .\\abc.exe
Get-Content input.txt | .\\abc.exe
it keeps printing 10 which corresponds to ASCII "line feed" character. Get-Content input.txt | .\\abc.exe
它会继续打印10,它对应于ASCII“换行”字符。
Apparently PowerShell has multiple places where encoding needs to be set before everything starts to work fine. 显然,PowerShell有多个地方需要设置编码,然后一切才能开始正常运行。
Finally I came up with this solution - add lines that are below this text to your PS profile file: 最后,我想出了这个解决方案-在此文本下方的行添加到您的PS配置文件中:
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
chcp 1250 // Change here for preferable Windows Code Page. 1250 is Central Europe
$OutputEncoding = [Console]::OutputEncoding
Clear-Host // clear screen because chcp prints text "Active code page: (code page)"
After including these lines Get-Content
started to behave correctly. 包含这些行之后, Get-Content
开始正确运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.