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.

See also  5 Benefits of Using Time Tracking Software

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist