如何删除文件

时间:2016-04-01 16:48:18

标签: c++ if-statement ifstream ofstream

对于我正在创建的一个项目,我创建了一个包含一些关键字的课程数据库文件,让我知道如果我到达那一行然后删除所有内容,直到找到下一行。在这种情况下,行是“Descriptionstart”和“Descriptionend”。我无法真正更改文件,因为我在开发过程中走得太远,无法更改文件中的任何内容。这是我到目前为止所做的:我几乎运行程序并输入“计算机逻辑电路”,然后删除所有行,直到“Descriptionstart”。我所评论的是我正在玩并通过调试器来查看发生了什么。但此时它有点混乱

int main() 
{
    ifstream myfile("coursedatabase.csv");
    ofstream myfile2("outfile.csv");
    string line;
    string temp = ""; 
    int skip = 0;
    string dropcourse;
    //string name = "Computer Logic Circuits";

    cout << "Enter course to drop by course name: ";
    getline(cin, dropcourse);

    while (getline(myfile, line)) 
    {
        if ((line != dropcourse) && !(skip > 0)) 
        {
            myfile2 << line << endl;

        }
        else 
        {
            if (skip == 0) 
            {
                skip = 4;
            }
            else 
            {
                --skip;
            }
        }
        /*if (line == "Descriptionstart")
        {
            while (getline(myfile, line))
            {
                if (line == "Descriptionend")
                {

                }
            }
            myfile2 << line << endl;
        }*/
    }

    myfile.close();
    myfile2.close();

    remove("coursedatabase.csv");
    rename("outfile.csv", "coursedatabase.csv");

}

以下是列表中的课程示例。

start
Electric Circuit Theory I
ENGI-1236-FA
Year 1
2
0
Descriptionstart
Fundamentals of electromagnetism and circuit analysis; network theorems; 
properties of resistors, capacitors and inductors; transients in RL and RC networks; 
introductory magnetic circuits and ideal op-amp circuit analysis.
Descriptionend
Dr. Laura Curiel
end

start
Computer Logic Circuits
ENGI-1637-FA
Year 1
2
0
Descriptionstart
Introduction to fundamental concepts of digital logic circuits and design with Verilog HDL. Topics include 
principles of number systems, operations, codes, logic gates, Boolean algebra and logic simplification, PAL 
and PLD based combinational logic functions, synchronous and asynchronous logic circuits, state transition 
diagrams, latches, flip-flops, counters, shift registers, memory, Mealy and Moore finite state machines.
Descriptionend
Dr. Ehsan Atoofian
end

start
Intro to Microcontrollers
ENGI-1232-WA
Year 1
2
0
Descriptionstart
Hardware and software aspects of microcontrollers and their applications in embedded systems; assembly 
language programming; architecture and addressing structures; serial and parallel input/output interfaces; 
timer programming; memory interfacing; interrupts and interrupt service routines; programming in C for 
microcontrollers; ADC, DAC and sensor interfacing.
Descriptionend
Dr. Ehsan Atoofian
end

1 个答案:

答案 0 :(得分:0)

删除文件中文本的唯一方法是创建另一个没有删除文本的文件。文件不会自动压缩以填补空白。

将图片文件作为字符数组。在数组中删除文本时,您需要将有效字符复制到新数组或移动删除文本后面的字符以覆盖已删除的文本。您可以使用文件执行此操作,但效率不高。

大多数应用程序通过写入新文件来删除文件中的文本。