Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Mar 27, 1997

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 the language 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 file after 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] = '\0'  ; // 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] != '\0') // 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] = '\0';
	}

	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 compare output easily with the input. This can be easily modified to write to the same file. You can also use the same method to sort your file; all you have to do is sort char *lines[] before calling writeFile.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date