C++ remove line from a file

In this C++ tip, I would like to show you how to remove a line of text from a text file. To remove a specific line from a file, you will use the ifstream class to read every line of the file. While you are reading a line, you can check whether the line is to be deleted or not. If it is not the line to be deleted, you write it to a temporarily file using ofstream class. After you complete reading and writing process, you use the remove() function to delete the source file and use the rename() function to rename the temporary file to the source file.

void removeLine(char* sourcefile,int line){
     ifstream infile;
     char tempPath[100]="D:/tempfile.txt";
     infile.open(sourcefile,ios::in);
     if(infile){
        int numLine=countLine(sourcefile);
        if(numLine<line){
           cout<<"\nNo line to delete\n.";
           return;
        }
        ofstream outfile;
        outfile.open(tempPath,ios::out);
        char data[100];
        int i=0;
        while(infile.getline(data,100)){
           i++;
           if(i==line) continue;
           outfile<<data<<"\n";
        }
        outfile.close();
     }
     infile.close();
     remove(sourcefile);
     rename(tempPath,sourcefile);
   }
   int countLine(char* sourcefile){
     ifstream infile;
     infile.open(sourcefile,ios::in);
     char data[100];
     int line=0;
     while(infile.getline(data,100)) line++;
     return line;
   }

Posted by: Dara | post date: 05-26-2015 | Subject: C++ Programming Language

write programming tip