从 C++ 中读取垃圾文件

Read a trash file from C++

#include <bits/stdc++.h>
using namespace std;

int main(int count, char* argv[])
{
  if(count!=2)
  {
    // print_syntax(argv[0]);
  }
  else if(count==2)
  {
    string file_name=argv[1];
    // cout<<file_name<<endl;
    string file_directory="~/.local/share/Trash/info/"+file_name+".trashinfo";
    cout<<file_directory<<endl;
    ifstream myReadFile;
     myReadFile.open(file_directory);
     char output[100];
     if (myReadFile.is_open()) 
     {
        cout<<"here";
     while (!myReadFile.eof()) 
     {


        myReadFile >> output;
        cout<<output;


     }
    }
    else
    {
        cout<<"Not working";
    }
    myReadFile.close();
}
}

我正在尝试从垃圾箱中读取一个文件,该文件还有两个子文件夹,信息文件夹包含已删除文件的元数据,扩展名为 .trashinfo

但是由于某些原因,我无法在该程序中打开该文件。

root@kali:~/projects/Linux-Commands/Restore# ./a.out hero
~/.local/share/Trash/info/hero.trashinfo
Not working
root@kali:~/projects/Linux-Commands/Restore# vi ~/.local/share/Trash/info/hero.trashinfo

通过使用这个 vi 命令,我可以轻松地在终端中打开它,甚至可以对其进行编辑。

您不能在 C++ 程序中使用 ~ 来引用用户的主目录 - 此字符由 shell 扩展,而不是OS 一般。

您应该指定一个绝对路径,或者使用 getenv,如图

一个更简单的修复方法是将文件的完整路径传递给您的程序,而不用担心在您的程序(file_directory = argv[1],而不是您当前的程序)中修改它。然后,从 shell,您可以输入

a.out "~/.local/share/Trash/info/hero.trashinfo"

和 shell 将按您的预期展开 ~。引号是为了确保如果路径中有空格,完整路径将作为单个字符串传入,而不是被 shell 拆分为多个参数。