文件系统设计

#include 

using namespace std;

void ModeChange(const string &filename, const string &mode)
{
    fileSys[filename].isReadable  = !(mode == "w" || mode == "a") ?  1 : 0;
    fileSys[filename].isWriteable = mode != "r" ? 1 : 0;
    if (mode.find("w") != string::npos) {
        fileSys[filename].cont.clear;
    }
    fileSys[filename].index = mode.find("r") != string::npos ? 0 : fileSys[filename].cont.size();
}

int open(const string &filename, const string &mode)
{
    bool uOpe = fileSys.find(filename) == fileSys.end() && mode.find("r") != string::npos || fileSys[filename].isOpen;
    if (uOpe) {
        return -1;
    }
    fileSys[filename].isOpen = 1;
    ModeChange(filename, mode);
    return 0;
}

int close(const string &filename)
{
    if (fileSys.find(filename) != fileSys.end() && fileSys[filename].isOpen) {
        fileSys[filename].isOpen = 0;
        return 0;
    }
    return -1;
}

int Write(const string &filename, const string &content)
{
    if (fileSys.find(filename) == fileSys.end() || !fileSys[filename].isOpen || !fileSys[filename].isWriteable) {
        return -1;
    }
    string temp = fileSys[filename].cont.substr(0, fileSys[filename].index) + content;
    fileSys[filename].index = temp.size();
     if (temp.size() < fileSys[filename].cont)
    {
        temp += fileSys[filename].cont.substr(temp.size());
    }
    fileSys[filename].cont = temp;
    return temp.size();
}

string ReadAll(const string &filename) 
{
    if (fileSys.find(filename) == fileSys.end() || !fileSys[filename].isWriteable) {
        return -1;
    }
    if (fileSys[filename].cont.empty()) {
        return "";
    }
    return fileSys[filename].cont;
}

你可能感兴趣的:(开发语言)