尝试删除()时权限被拒绝

时间:2020-09-25 03:52:08

标签: c++ fstream

Screenshot我花了4个多小时来尝试解决此错误。 这是我的代码:

#include <iostream>
#include <string>
#include <fstream>
#include <cstring>

using namespace std;

void UpdateFile(int line, string data_)
{
    //create new file
    fstream newFile("data.new");
    int i = 0;

    string data;
    ifstream file("data.txt");

    //write to newFile
    while (getline(file, data))
    {
        if (i != line)
        {
            newFile << data << endl;
        }
        else
        {
            newFile << data_ << endl;
        }
        i++;
    }
    newFile.close();
    file.close();

    if (remove("data.new") != 0)
#pragma warning(suppress : 4996)
        cout << "Failed to delete" << ": " << strerror(errno) << '\n';
    rename("data.new", "data.txt");
}

void SetUp()
{
    remove("data.txt");
    ofstream file("data.txt");

    file << "#ACCOUNT" << endl;
    file << "0" << endl;

    file.close();
}

void CreateAcc()
{
    string n;
    ifstream data("data.txt");

    data >> n >> n;

    ofstream newAcc("Accounts/account" + n + ".txt");
    UpdateFile(1, to_string(stoi(n) + 1));

    //system("cls");
    cout << "Enter Name" << endl;
    string name;
    cin >> name;

    newAcc << "#ACCOUNT NUMBER " + n << endl;
    newAcc << name;
}

void Menu()
{
    int input;
    cout << endl << "           " << "CUSTUMER ACCOUNT BANKING MANAGEMENT 
    ACCOUNT" << endl << endl;

    //TODO
    cout << "1) Create new account" << endl;
    cout << "2) Update information of an existing account" << endl;

    cin >> input;
    if (input == 1)
    {
        CreateAcc();
    }
}

int main()
{
    fstream file;
    file.open("data.txt", fstream::out);

    if (file.is_open())
    {
        string tp;
        file >> tp;
        if (tp != "#ACCOUNTS")
            SetUp();
    }
    Menu();
}

我做了在其他线程上发现的所有事情。我已经用完整的路径代替了它,甚至移动了我的项目,创建了一个新的并将代码放入其中,没有任何效果。您有什么想法会导致这种情况吗?

我编辑了我的帖子。现在,它包含了我的所有代码,因此,如果您想尝试一下,请随意。

1 个答案:

答案 0 :(得分:0)

经过大量调试后,我发现了问题。 造成问题的原因是我在打开文件时没有关闭文件。要删除文件,绝对不能打开。