与在命令行上使用文件名进行输入和输出的程序交互的最佳方式是什么?
我需要与一些期望传递输入或输出文件名的可执行文件进行交互:
./helper in.txt out.txt
执行此操作的标准(最好是跨平台)方法是什么?
我可以在 /tmp
目录中创建大量临时文件,但我担心创建大量文件可能会导致一些问题。另外,我希望能够安装我的程序,而不必担心以后的权限问题。
我也可以只是针对 Unix 并尝试使用管道等来寻求解决方案。但是,我认为我无法找到一个具有良好的未命名管道的解决方案。
我的替代方法是将输入管道输入到标准输入(我需要的所有可执行文件也以这种方式接受它)并从标准输出获取结果。然而,它们提供给 stdout 的输出都是不同的,我需要手动编写大量适配器来使其统一(通过文件的输出遵循相同的标准)。不过,我不喜欢这会将我的程序锁定为几种格式。
I need to interface with some executables that expect to be passed filenames for input or output:
./helper in.txt out.txt
What is the standard (and preferably cross-platform) way of doing this?
I could create lots of temporary files int the /tmp
directory, but I am concerned that creating tons of files might cause some issues. Also, I want to be able to install my program and not have to worry about permissions later.
I could also just be Unix specific and try to go for a solution using pipes, etc. But then, I don't think I would be able to find a solution with nice, unnamed pipes.
My alternative to this would be piping input to stdin (all the executables I need also accept it this way) and get the results from stdout. However, the outputs they give to stdout are all different and I would need to write lots of adapters by hand to make this uniform (the outputs through files obey a same standard). I don't like how this would lock in my program to a couple of formats though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不一定有正确或错误的答案。读取/写入标准输入/输出可能更干净并且不使用磁盘空间。不过,使用临时文件也没有问题,只要安全地进行即可。具体而言,请参阅
mktemp
和mkstemp
手册页,了解可让您创建临时文件以供短期使用的函数。只需稍后清理它们(取消链接
),就可以使用和操作临时文件了。There isn't a right or wrong answer necessarily. Reading/writing to stdin/out is probably cleaner and doesn't use disk space. However, using temporary files is just fine too as long as you do it safely. Specifically, see the
mktemp
andmkstemp
manual page for functions that let you create temporary files for short-term usage. Just clean them up afterward (unlink
) and it's just fine to use and manipulate temp files.