检查 Windows 文件是否重定向到自身 [英] Check if Windows file is redirected to itself
问题描述
我想弄清楚如何测试文件是否被重定向到自身,例如<代码>.\command.exe file1 >文件1
I'm trying to figure out how I can test if a file is being redirected to itself, e.g. .\command.exe file1 > file1
在 *nix 世界中,我只会使用这样的东西:
In the *nix world, I'd just use something like this:
// Language agnostic...
if (file_dev == out_dev && file_ino == out_ino) {
printf("%s\n", "same file!");
}
但是在 Windows 中,如果我尝试这样做:
But in Windows, if I try to do this:
// This (language) is Go...
// create fileStat...
// now stat stdout
outStat, err := os.Stdout.Stat()
// error check
if os.SameFile(fileStat, outStat) {
fmt.Println("same file!")
}
...我收到 IncorrectFunction
错误.
...I get the IncorrectFunction
error.
我读了这个(https://stackoverflow.com/a/21070042/2967113)问题,以及从什么我猜你不能统计stdout
?
I read this (https://stackoverflow.com/a/21070042/2967113) question, and from what I gather you can't stat stdout
?
这是一个主要与语言无关的问题——我可以将任何内容翻译成 Go(我使用的语言).我最关心的是如何,使用 Windows 的 ABI(API?),我会发现标准输出被重定向到哪里.
This is a mostly language agnostic question -- I can translate whatever to Go (the language I'm using). I'm mostly concerned about how, using Windows' ABI (API?), I would find where stdout is being redirected to.
推荐答案
这个答案是特定于 Windows 的,但因为你已经标记了windows",我认为没关系.
This answer is Windows-specific but as you've tagged "windows" I figure that's ok.
我对 Go 无能为力,但在 C/C++ 中你可以这样做:
I can't help with Go, but in C/C++ you can do something like this:
#include <tchar.h>
#include <Windows.h>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t chPath[MAX_PATH];
if (GetFinalPathNameByHandle(GetStdHandle(STD_OUTPUT_HANDLE), chPath, MAX_PATH, 0))
std::wcout << L"stdout = " << chPath << std::endl;
else
std::cout << "stdout not redirected" << std::endl;
return 0;
}
如果 stdout 是控制台句柄,
GetFinalPathNameByHandle
将失败,但如果它被重定向到一个文件,它将返回文件路径.
GetFinalPathNameByHandle
will fail if stdout is a console handle, but if it's been redirected to a file it will return the file path.
这篇关于检查 Windows 文件是否重定向到自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!