-1
#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();
}
}

I am trying to read a file from trash which further has two subfolders, the info one containing meta data for deleted file with an extension of .trashinfo

But due to some reason, I am not able to open that file in this program.

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

By using this vi command, I can easily open it in the terminal and even edit it.

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

3

You can't use ~ to refer to the user's home directory in a C++ program - this character is expanded by the shell, not the OS in general.

You should either specify an absolute path, or use getenv as shown here.

An easier fix is just to pass the full path to the file to your program, and not worry about modifying it inside your program (file_directory = argv[1], rather than your current). Then, from the shell, you can type

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

and the shell will expand ~ as you expect. The quotation marks are to ensure that if you have spaces in your path, the full path is passed in as a single string rather than being split up by the shell into multiple arguments.

hnefatl
  • 5,860
  • 2
  • 27
  • 49