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

标签 c++ linux filesystems ncurses

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

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

display /home -> user selects /folder1 -> display /folder1 -> user selects /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;
}

最佳答案

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

关于c++ - 如何使用 C++ 浏览目录以创建文件资源管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47998956/

相关文章:

C#/C++ : Launch an application and handle its I/O calls to the system

c++ - 我如何强制启动板使用 g++ 4.7 或更高版本构建我的包

c++ - 如何在 C++ 中创建重复直到循环?

linux - Linux 4.14 中的 NETLINK_NFLOG 支持

linux - 菜单的 Shell 脚本

c - 为什么我的TTL值每次都增加2? (C Socket编程)

linux - 是否有一个Linux文件系统,也许是fuse,它可以将目录大小指定为其内容及其子目录的大小?

c++ - 错误 C3861 : 'aligned' : identifier not found

C++多线程解码音频数据

actionscript-3 - Adobe AIR 和不同的操作系统文件系统