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

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

本文关键字:创建 文件 资源管理器 何使用 浏览      更新时间:2023-10-16

我正在尝试使用我的课程中的Ncurses在C 中创建一个文件资源管理器。目前,我正在尝试找到一种浏览文件系统的方法,并找出" x"是否是文件/目录并采取相应的行动。

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

display/home->用户选择/folder1-> display/folder1->用户选择/文档 -> ...

我已经阅读了有关脚本的信息,并试图创建一个" CD/HOME"脚本,但它不起作用。在某个地方,我读到execve()函数可能起作用,但我不明白。我觉得我正在思考这个问题,坦率地说,我被卡住了。

编辑:本质上,我想找到:如何制作它,以便我的程序在"路径"上开始,以便当我调用getCwd()时,它会返回"路径",而不是程序的实际路径。<<<<<<<<<<<</p>

#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 DIRECTORIOn";
    }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仅在执行此操作(或子过程)的程序中持续存在。它不会导致外壳改变。有一个应用程序(WCD),它可以执行类似于您正在尝试的操作,将导航与shell脚本结合在一起。