如何使用c ++在目录中导航以创建文件资源管理器

问题描述 投票:2回答:2

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

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

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

我读过有关脚本的文章并试图创建一个“cd / home”脚本,但它不起作用。在某处我读到execve()函数可能有效,但我不明白。我有一种感觉,我正在思考这一点,坦率地说,我被困住了。

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

#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;
}
c++ linux filesystems ncurses
2个回答
0
投票

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


0
投票

chdir仅在执行它(或子进程)的程序中持续存在。它不会导致shell更改。有一个应用程序(wcd)可以执行类似于您正在尝试的内容,它将导航与shell脚本相结合。

© www.soinside.com 2019 - 2024. All rights reserved.