command-line - 给定 rust 中的绝对路径,如何上传文件?
问题描述
我的目标是使用 Rust 编程语言在 ipfs.io 上上传文件。我正在触发一个命令行工具来执行此操作,并且该命令本身可以工作,但是当使用 Rust 实现时,它会失败。
实际的命令是:
➜ ~ ipfs add ~/dev/learning-rust/upload-file-to-ipfs/src/main.rs
added QmPUGDCiLvjEiETVDVMHqgJ8xxtQ5Hu7YEMzFqRfE8vDfq main.rs
现在,我的 Rust 代码是:
use std::io;
use std::process::Command;
fn main() {
// ask user to provide the file path to be uploaded on ipfs
println!("Please enter the file path to upload on IPFS: ");
let mut file_path = String::new();
io::stdin()
.read_line(&mut file_path)
.expect("Failed to read temperature.");
// uploading a file
let output = Command::new("ipfs")
.arg("add")
.arg(file_path)
.output()
.expect("ipfs command failed to start");
println!("Output is: {:?}", output);
// println!("The hash digest is: {:?}", output.stdout);
}
这失败并出现以下错误:
Output is: Output { status: ExitStatus(ExitStatus(256)), stdout: "", stderr: "Error: lstat /Users/aviralsrivastava/dev/learning-rust/upload-file-to-ipfs/src/main.rs\n: no such file or directory\n\nUSAGE\n ipfs add <path>... - Add a file or directory to ipfs.\n\n ipfs add [--recursive | -r] [--quiet | -q] [--quieter | -Q] [--silent] [--progress | -p] [--trickle | -t] [--only-hash | -n] [--wrap-with-directory | -w] [--hidden | -H] [--chunker=<chunker> | -s] [--pin=false] [--raw-leaves] [--nocopy] [--fscache] [--cid-version=<cid-version>] [--] <path>...\n\n Adds contents of <path> to ipfs. Use -r to add directories (recursively).\n\nUse \'ipfs add --help\' for more information about this command.\n\n" }
如何上传给定绝对和/或相对路径的文件并在打印语句中返回哈希?
解决方案
您的问题不在于Command
with read_line
,它将读取所有字节,包括换行符(请参见此处)。因此,您的路径最终包含换行符,这就是找不到文件的原因。
要解决此问题,您需要确保文件路径不包含尾随换行符,例如在将其传递给命令之前对其调用trim_end 。
推荐阅读
- redirect - NextJS 静态页面目录更改名称使用 i18n
- sql - PostgreSQL 说明:如果某些表有数百万行,我如何查看计划?
- python - 如何重塑熊猫中的测量数据
- r - cox模型中时间无关和时间相关协变量之间的相互作用
- javascript - ASPNET Core MVC ajax 未正确传递数据
- typescript - “从不”类型上不存在属性“地图”
- google-sheets - 处理电子表格中添加的新行
- citrus-framework - 如何测试返回soapfaultclientexception的soap端点
- node.js - 两个类之间的打字稿复杂映射
- android - 如何更改 AppMeasurementInstallReferrerReceiver 权限