c++ - C++ 目录列表表现得很奇怪
问题描述
所以我在 Linux 上做一个 CMD 实现,但我遇到了一些问题。如果我使用这样的 CD 命令更改工作目录: /$CD home 然后如果我运行 ls 命令而没有任何内容 /home$ls 它不列出任何内容,除非我执行此命令:cd ./ 或此命令:ls ./ 并且它可以工作再次。主.cpp:
#include <iostream>
#include <string>
#include <filesystem>
#include <boost/filesystem.hpp>
#include <sys/types.h>
#include <dirent.h>
#include "commands.h"
#include <vector>
#include <unistd.h>
using namespace std;
string arr[4];
string out[4];
string dir("/");
void sep(string line)
{
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 4){
ssin >> arr[i];
++i;
}
for(i = 0; i < 4; i++){
out[i]=arr[i];
}
}
int main()
{
//startup text
string input;
cout << "Linux\n" << system("uname -r") <<"\n";
while (true) {
cout << std::filesystem::current_path();
getline (cin,input);
sep(input);
if (input=="ver")
{
ver();
}
//exit
else if (out[0]=="exit")
{
return 0;
}
else if (input=="")
{
}
//echo
else if (out[0]=="echo")
{
cout << out[1] << "\n";
}
else if (out[0]=="ls"||out[0]=="dir")
{
if (out[1]==""){
list_dir(std::filesystem::current_path());
}
else
list_dir(out[1]);
}
else if (out[0]=="clear")
{
printf("\033[2J");
printf("\033[H");
}
else if (out[0]=="exec")
{
string name=out[1];
const char *namecc=name.c_str();
open(namecc);
}
else if (out[0]=="cd")
{
const char *chd=out[1].c_str();
cout << chd << "\n";
chdir(chd);
if (chdir(chd)==-1)
{
cout << "chdir() Returned -1,directory not exist or error\n";
}
}
else cout << "Bad command or file name\n";
}
}
命令.h:
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sstream>
#include <filesystem>
#include <unistd.h>
#include <boost/filesystem.hpp>
#include <dirent.h>
#include <stdio.h>
using namespace std;
using namespace boost::filesystem;
namespace fs = std::filesystem;
void ver()
{
std::cout << "CMD for linux 1.0\n";
}
int list_dir(string ddddd) {
DIR *d;
struct dirent *dir;
const char* p=ddddd.c_str();
d = opendir(p);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
}
closedir(d);
}
return 0;
}
int cd(string aa)
{
const char *bbbbb=aa.c_str();
DIR* a=opendir(bbbbb);
if (a)
{
return 0;
}
else return 1;
}
int open(const char* file)
{
FILE *handle = popen(file, "r");
if (handle == NULL) {
return 1;
}
char buf[64];
size_t readn;
while ((readn = fread(buf, 1, sizeof(buf), handle)) > 0) {
fwrite(buf, 1, readn, stdout);
}
pclose(handle);
return 0;
}
顺便说一句,我仍然不太擅长 C++,所以如果代码未优化,请提供一些关于如何使它变得更好的建议,谢谢。
解决方案
推荐阅读
- java - 詹金斯连接被拒绝
- laravel - Laravel Nova - 从 BelongsToMany 字段中隐藏视图和编辑
- c# - DbContextOptionBuilder 不包含 UseSqlServer 的定义 - VS 2017 / VS for Mac
- adfs - ADFS、SharePoint 本地
- email - SimpleEmail 强制 SMTP 到端口 465
- java - Spring Security Crypto 模块 - BadPaddingException:给定最终块未正确填充
- php - 通过 Python 上的服务器进行串行数据通信
- rust - 如何直接将有限的字节从读取器复制到写入器
- php - 面临这个问题“上传的文件超过了php.ini中的upload_max_filesize指令。”
- android - 有没有办法为多个控件编写相同的 onclick 函数?