Writing and deleting text file lines, and bubble sorting alphabetically

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

Answer:
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:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a