0

I have a CSV file and I want to delete a specific line in it. The way I want to do this is by reading the file line by line and checking if the first element of the line is equal to a variable. If it's equal => remove the line.

// get the project name from the combo box
QVariant projectName = ui->projectCombo->currentText();

QFile projectFile(CSV File);
// checks if file is valid and can open
if(!projectFile.open(QIODevice::ReadOnly)) {
    cout << "Error: can't copen file" << endl;
} else {
    cout << "File open successfully" << endl;
}

QTextStream in(&projectFile);
while(!in.atEnd()) {
    QString line = in.readLine();
    // Get the first element from line
    QString firstElement = line.split(',').first();
    // Check if firstElement is equal to the variable projectName
    if (firstElement == projectName.toString()) {
        // Delete current line
    }
}

I'm doing this because I want to update specific data on that line. I know Qt, let alone c++, can't do this. So I thought I get the line from the file, put it in a data structure, delete it from the file, edit the desired data inside the data structure and then append to file the changed data from the data structure

  • 2
    A standard way to modify record oriented files is to read one line, process it, and write the result (if any) to a new file. Then, if you want, when everything is complete delete the old file and rename the new one. – Bo Persson Apr 15 '18 at 23:51
  • @BoPersson Thought about it, but that's inefficient and messy ... – Hadi Farhat Apr 15 '18 at 23:54
  • @HadiFarhat The normal thing is to read all the data in ram, modify the data (in your case delete that line), and overwrite the same file. Although it is inefficient it is the normal way. – eyllanesc Apr 15 '18 at 23:57
  • 1
    Possible duplicate of [Deleting specific line from file](https://stackoverflow.com/questions/26576714/deleting-specific-line-from-file) – eyllanesc Apr 15 '18 at 23:58

1 Answers1

0

If you want to delete according to the line number you can use this

m_File.close();
QString qCommand = "sed -i 2d "+fileName;
string command = qCommand.toUtf8().constData();
system(command.c_str());
m_File.open(FileName.c_str(), ios::out|ios::app);

Make a function like this, and pass the necessary parameters. After you can even append to the same file, as its opened inside the same function