首页 > 解决方案 > 从文件中删除一行而不创建新文件

问题描述

我正在尝试从文件中删除一行而不创建新文件。例如,在修改之前的文件中,它将是:

This
is
a
file

之后是:

This
a
file

但是,按照我目前正在尝试的方式,会发生什么

This
  a
file

我知道我可以通过只将我想要的内容写入另一个文件然后重命名该文件并删除旧文件来做到这一点,但我想知道除此之外是否还有其他方法。

我试过使用

if (string::npos != line.find(SPSID))
{
        iPos = (pos - line.size() - 2);

    stream.seekg(iPos);
    for (int i = (pos - line.size() - 2); i < pos; i++)
    {
        //Sets input position to the beginning of the current line and replaces it with NULL
        stream.put(0);
    }
    stream.seekp(iPos);
    pos = stream.tellp();
}

以及替换stream.put(0);stream.write(nullLine, iPos); 但都没有工作。

int Delete(string fileName, string SPSID)
{
    //Variables
    string line;
    char input[MAX_CHAR];
    fstream stream;
    streamoff pos = 0;
    streamoff iPos = 0;

    //Opening and confirming opened
    stream.open(fileName);

    if (!stream.is_open())
    {
        cout << "File Did not open.\n" << endl;
        return -1;
    }

    //Loops until the end of the file
    do
    {
        //Gets one line from the file and converts it to c++ string
        stream.getline(input, MAX_CHAR, '\n');
        line.assign(input);

        //Finds the current output position (which is the start of the next line)
        pos = stream.tellp();

        //Finds and checks if the SPSID is in the string. If it is then print to screen otherwise do nothing
        if (string::npos != line.find(SPSID))
        {
            iPos = (pos - line.size() - 2);

            stream.seekg(iPos);
            for (int i = (pos - line.size() - 2); i < pos; i++)
            {
                //Sets input position to the begining of the current line and replaces it with ""
                stream.put(0);
            }
            stream.seekp(iPos);
            pos = stream.tellp();
        }

    } while (stream.eof() == false);    //Checks that the end of the file has not been reached

    stream << "Test" << endl;

    //Resets the input and output positions to the begining of the stream
    stream.seekg(0, stream.beg);
    stream.seekp(0, stream.beg);

    //Closing and Confirming closed
    stream.close();

    if (stream.is_open())
    {
        cout << "File did not close.\n" << endl;
        return -2;
    }


    return 0;
}

我可能不得不制作一个新文件并重命名它,但我认为这仍然值得询问这是否可能。:/

标签: c++filedelete-file

解决方案


推荐阅读