首页 > 解决方案 > 尝试删除()时权限被拒绝

问题描述

屏幕截图我花了 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();
}

我做了我在其他线程上找到的一切。我已经用完整的路径替换了路径,我什至移动了我的项目,我制作了一个新的并将这段代码放入其中,没有任何效果。你知道什么会导致这种情况吗?

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

标签: c++fstream

解决方案


经过大量调试,我发现了问题。导致问题的原因是我打开文件而不关闭它们。删除文件是不能打开的。


推荐阅读