如何使用 C++ 浏览目录以创建文件资源管理器

How to navigate through directories using c++ to create a file explorer

我正在尝试使用 Ncurses 在 C++ 中为我的 class 创建一个文件资源管理器。目前我正在尝试找到一种方法来浏览文件系统并找出 'x' 是否为 file/directory 并采取相应的行动。

问题是我找不到一种方法来按照我喜欢的方式浏览目录。例如,在下面的代码中,我从“.”开始。然后在保存所述目录及其文件的一些信息的同时阅读它。但我想在每次程序运行时将 cwd 定义为“/home”,然后从那里开始探索用户想要的任何内容:

display /home -> user selects /folder1 -> display /folder1 -> user selects /documents -> ...

我已经阅读了有关脚本的内容并尝试创建一个 "cd /home" 脚本,但它不起作用。我在某处读到 execve() 函数可能有效,但我不明白。我有一种感觉,我想太多了,坦率地说,我被困住了。

编辑:本质上我想找到:如何使我的程序从 "path" 开始,这样当我调用 getcwd() 它时 returns "path"而不是程序的实际路径。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
#include <linux/limits.h>
#include <iostream>
#include "contenido.cpp"
using namespace std;

//Inicia main

int main(int argc, char const *argv[]) {
  DIR *dir;                       //dir is directory to open
  struct dirent *sd;
  struct stat buf;                //buf will give us stat() atributes from 'x' file.
  char currentpath[FILENAME_MAX]; //currentpath
  contenido dcont;

  //system (". /home/rodrigo/Documentos/Atom/Ncurses/Proyecto/beta/prueba.sh");

  if((dir = opendir(".")) == NULL){ /*Opens directory*/
    return errno;
  }
  if(getcwd(currentpath, FILENAME_MAX) == NULL){
    return errno;
  }

  while ((sd= readdir(dir)) != NULL){ /*starts directory stream*/
    if(strcmp(sd -> d_name,".")==0 || strcmp(sd -> d_name,"..") ==0){
        continue;
    }

    //Gets cwd, then adds /filename to it and sends it to a linked list 'dcont'. Resets currentpath to cwd
    //afterwards.
    getcwd(currentpath, FILENAME_MAX);
    strcat(currentpath, "/");
    strcat(currentpath, sd->d_name);
    string prueba(currentpath);
    //std::cout << currentpath << '\n';
    dcont.crearnodo(prueba);
    if(stat(currentpath, &buf) == -1){
      cout << currentpath << "\n";
      perror("hey");
      return errno;
    }
    getcwd(currentpath, FILENAME_MAX);

    //Prints Files and Directories. If Directory prints "it's directory", else prints "file info".
    if (S_ISDIR(buf.st_mode)) {
      cout << sd->d_name << "\n";
      cout << "ES DIRECTORIO\n";
    }else
    cout << sd->d_name << "\n";
    cout <<"Su tamaño es: " << (int)buf.st_size << "\n";
    //system("ls");

  }


  closedir(dir);
  dcont.mostrardircont(); //prints contents of the linked list (position in list and path of file).
  return 0;
}

要更改当前工作目录,请使用 chdir 如果你想将 cwd 更改为“/home” chdir("/home");

chdir 只存在于执行它的程序(或子进程)中。它不会导致 shell 改变。有一个应用程序 (wcd) 可以执行您正在尝试的操作,它将导航与 shell 脚本结合在一起。