This is a simple example of how to delete a line from a text file. In order to do that you have to completely rewrite the file, leaving out the line(s) you want to delete. First open the input file, then open an output file (doesn't matter what filename you give it as long as its a legal file name for your computer system). After read/write loop finishes, close both files, delete the original (or rename it if you don't want to delete it) and rename the new temp file to the original filename.
delete a line from a text file
#include <cstdio>
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string line;
// open input file
ifstream in("infile.txt");
if( !in.is_open())
{
cout << "Input file failed to open\n";
return 1;
}
// now open temp output file
ofstream out("outfile.txt");
// loop to read/write the file. Note that you need to add code here to check
// if you want to write the line
while( getline(in,line) )
{
if(line != "I want to delete this line")
out << line << "\n";
}
in.close();
out.close();
// delete the original file
remove("infile.txt");
// rename old to new
rename("outfile.txt","infile.txt");
// all done!
return 0;
}
dnalor 0 Newbie Poster
aastephen 0 Newbie Poster
aastephen 0 Newbie Poster
majestic0110 187 Nearly a Posting Virtuoso
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.