【问题标题】:Read a trash file from C++从 C++ 读取垃圾文件
【发布时间】:2017-07-24 10:41:06
【问题描述】:
#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 命令,我可以很容易地在终端中打开它,甚至可以编辑它。

【问题讨论】:

  • '~' 由 shell 扩展,如果您从 C++ 程序执行此操作,则它不起作用。请查看stackoverflow.com/questions/2910377/…
  • ~ 在这种情况下不能用于引用用户的私人目录。
  • 确实,我今天学到了一些新东西。谢谢。

标签: c++ linux file-handling recycle-bin


【解决方案1】:

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

您应该指定一个绝对路径,或者使用getenv,如here 所示。

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

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

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

【讨论】:

  • 对访问该文件有帮助吗?
  • a.out ~/.local/share/Trash/info/hero.trashinfo 这是我愿意使用的技巧,用户只需输入文件名并提供时间已删除
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
  • 2016-02-06
  • 1970-01-01
相关资源
最近更新 更多