我正在尝试创建一个模拟文件夹和文件创建的程序。我创建了一个类Folder,其属性为Folder *prev
,该属性应指向父Folder。
问题是我创建的每个文件夹始终指向当前文件夹。请检查cd()
和mkdir()
函数。
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <String>
#include <stdio.h>
using namespace std;
int MAX_PER_FOLDER = 100;
int MAX_FILES_PER_FOLDER = 100;
struct File;
class Folder {
public:
Folder() {}
string name;
int nFolders;
int nFiles;
File *files;
Folder *folders;
Folder * prev;
};
struct File {
string name;
int size;
Folder *folder;
string data;
};
void ls(Folder root) {
for (int i = 0; i < root.nFolders; i++) {
Folder temp = root.folders[i];
std::cout << " - " << temp.name << endl;
}
}
void mkdir(string name, Folder ¤t) {
Folder *temp = new Folder();
temp->name = name;
temp->prev = ¤t;
temp->nFolders = 0;
temp->nFiles = 0;
temp->folders = new Folder[MAX_PER_FOLDER];
temp->files = new File[MAX_FILES_PER_FOLDER];
current.folders[current.nFolders] = *temp;
current.nFolders++;
}
void cfile(string name, Folder ¤t, string data) {
File temp;
temp.name = name;
temp.folder = ¤t;
temp.data = data;
current.files[current.nFiles] = temp;
current.nFiles++;
}
void cd(string name, Folder ¤t) {
bool found = false;
if (name == ".." && current.prev != NULL) {
cout << "====";
current = *current.prev;
cout << "---";
found = true;
}
else {
for (int i = 0; i < current.nFolders; i++) {
Folder f = current.folders[i];
if (f.name == name) {
current = f;
found = true;
break;
}
}
}
if (found) {
cout << "Current dir: " << current.name << endl;
}
else
cout << "Directory does not exist" << endl;
}
int main()
{
Folder root = Folder();
root.folders = new Folder[MAX_PER_FOLDER];
root.nFiles = 0;
root.nFolders = 0;
root.prev = NULL;
root.name = "root";
mkdir("Test1", root);
mkdir("Test2", root);
mkdir("Test3", root);
ls(root);
cd("Test3", root);
mkdir("Test3.1", root);
mkdir("Test3.2", root);
mkdir("Test3.3", root);
ls(root);
cd("Test3.1", root);
mkdir("Test3.1.2", root);
mkdir("Test3.1.3", root);
mkdir("Test3.1.4", root);
cd("Test3.1.2", root);
cd("..", root);
ls(root);
system("PAUSE");
return 0;
}
问题在于创建的所有文件夹始终指向cd()
设置的当前文件夹,我相信它存在于以下行中:temp->prev = ¤t;
,因为创建该文件夹时可能会指向只有一个地址,即当前文件夹的地址。
谢谢!
答案 0 :(得分:1)
您的cd
命令用其他内容覆盖root
的内容。 (请与调试器联系!)
我看到三个选项:
Folders
的指针。这样就不可能意外覆盖文件夹内容。cd
函数以使用(可能是全局的)指针 指向“当前目录”。这确实意味着您必须更改cd
的所有用法。std::reference_wrapper
用于cd
,这样current = folder;
会更新current
指向的位置,而不会更改其内容。