Writing and deleting text file lines, and bubble sorting alphabetically

Writing and deleting text file lines, and bubble sorting alphabetically

How can I write and delete individual lines of a text file?Also, how can I bubble-sort the whole text file alphabetically?

There is no support in thelanguage to do either of these things.

However, there are many tricks that one can perform to make them happen. One is to handle all manipulations to the file in memory, then write the fileafter it has been manipulated. Here is an example of a function that deletes some lines from a file and writes it back.

#include #include void deleteLine(char *lines[],int lineNo){	lines[lineNo-1][1] = ‘’  ; // zero out the first char on line to be deleted}void writeFile(char *lines[],int maxLines,ostream &outFile){	for (int i = 0; i < maxLines; ++i)		if (lines[i][1] != '') // don't write deleted lines			 outFile << lines[i] << endl;}int main (){	char *lines[80]; // max number of lines is 80	// allocate space and zero out chars.	for(int i = 0; i < 80; ++i)	{		lines[i] = new char[80] ; // each line holds 80 chars			lines[i][1] = '';	}	ifstream inFile("testFile.txt");	for(int j = 0; inFile.getline(lines[j],80) && j < 80; ++j)		;	deleteLine(lines,2);	ofstream outFile("testFile.out");	writeFile(lines,80,outFile);	return 0;}
In this example I am writing out to a different file so that you can compareoutput easily with the input. This can be easily modified to write to the samefile. You can also use the same method to sort your file; all you have to do is sort char *lines[] before calling writeFile.

Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved