如何使用C 浏览目录以创建文件资源管理器
How to navigate through directories using c++ to create a file explorer
我正在尝试使用我的课程中的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脚本结合在一起。
相关文章:
- 如何从Windows控制台调用.exe(C++)以在不同的目录(或任何目录)中创建文件夹?
- 避免使用 boost::进程间::消息队列创建文件
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- 如何在软件代码中使用ofstream创建文件
- 在特定 Unicode 路径中创建文件
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- 即使使用 FILE_FLAG_DELETE_ON_CLOSE 属性创建文件,文件也会保留在磁盘上
- C++ 为每个结构{人}条目创建文件
- "Access is Denied" U盘上的创建文件()
- 在c++编程中的文件夹中创建文件
- 创建文件夹结构
- 在C++中创建文件夹
- 创建文件函数是否可以打开仅在WinObj实用程序中的全局目录下列出的设备的句柄?
- 使用 C++ 或 SDL 在 Android 中创建文件
- 如何检测哪些进程更改,重命名或创建文件?
- 如何在 Linux 中通过 C/C++ 以其他用户身份创建文件?
- 挂钩创建文件抛出异常:读取访问冲突
- UWP 创建文件2 ERROR_ACCESS_DENIED "NUL"
- 如何指定创建文件函数获取未缓存的结果?
- Open() 用于创建文件和打开现有文件.有人能分辨出其中的区别