[英]How to navigate through directories using c++ to create a file explorer
我正在嘗試使用Ncurses為我的課程在C ++中創建文件資源管理器。 當前,我正在嘗試找到一種在文件系統中導航並確定'x'是否為文件/目錄並采取相應措施的方法。
問題是我找不到他們想要的目錄導航方式。 例如,在下面的代碼中,我從“”開始。 然后在保存該目錄及其文件的某些信息的同時進行讀取。 但是我想在程序每次運行時將cwd定義為“ / home”,然后從那里瀏覽用戶想要的內容:
顯示/ home->用戶選擇/ folder1->顯示/ folder1->用戶選擇/ 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”);
chdir僅保留在執行該程序的程序(或子進程)中。 它不會導致外殼發生變化。 有一個應用程序( wcd ),其功能類似於您正在嘗試的操作,它將導航與Shell腳本結合在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.