我正在尝试制作两个不同的程序--一个是将笔记写到笔记文件中,另一个是读取笔记。这两个程序被称为Notes和Noteread。以下是这些程序的源代码。
// notes.cpp
include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
int main () {
time_t now = time(0);
char* dt = ctime(&now);
ofstream myfile;
std::cout << ": ";
string x{};
std::cin >> x;
myfile.open ("~/notes.txt", ios_base::app);
myfile << "---- " << dt;
myfile << x << '\n';
myfile << "\n";
myfile.close();
return 0;
} // noteread.cpp
#include <bits/stdc++.h>
int main() {
system("less ~/notes.txt");
} 它应该是这样工作的。
jingle@variable [time] [~/notes] [master *]
-> % notes
: hello
jingle@variable [time] [~/notes] [master *]
-> % noteread
( less program)
--- time
hello
jingle@variable [time] [~/notes] [master *]
-> %尽管它最终会这样做:
jingle@variable [time] [~/notes] [master *]
-> % notes
: hello
jingle@variable [time] [~/notes] [master *]
-> % noteread
/home/jingle/notes.txt: No such file or directory
jingle@variable [time] [~/notes] [master *]
-> %我调试的另一件事是生成notes.txt文件,然后运行程序,但结果是,像上面那样运行程序后,没有人找到文件,但文件是空的。这真的很奇怪,而且超出了我的理解。提前感谢!
发布于 2020-05-19 05:59:44
~/notes.txt不是一条“真正的”路径。当您在shell/终端中编写它时,它会扩展为/home/jingle/notes.txt。您没有在C++程序中编写任何代码来执行此操作。
我建议您使用相对路径,所以只使用notes.txt。记录这一事实,并使用任务的正确当前工作目录从命令行相应地调用您的程序。
发布于 2020-05-20 05:42:01
我使用std::getenv来解决我的问题。然后,我可以获得HOME变量并在我的程序中使用它。
https://stackoverflow.com/questions/61879482
复制相似问题