VB icon

Number lines in Text File v1.0

Email
Submitted on: 8/25/2016 10:15:00 PM
By: Ben128  
Level: Beginner
User Rating: Unrated
Compatibility: C++ (general), Microsoft Visual C++, UNIX C++
Views: 1417
 
     This code shows how to number each line in a text file, you can then use the DOS redirect to write the result to a file.Hope you find it usfull.
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
				
//**************************************
// Name: Number lines in Text File v1.0
// Description:This code shows how to number each line in a text file, you can then use the DOS redirect to write the result to a file.Hope you find it usfull.
// By: Ben128
//**************************************

// Numbers line from a text file.
// By DreamVB
#include <iostream>
#include <stdio.h>
using namespace std;
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{ 
	FILE *fp = NULL;
	char line[255];
	char sLen[10];
	int i = 1;
	int len = 0;
	//Check for filename.
	if(argc != 2){
		cout << "Usage: " << argv[0] << " <Filename>";
		exit(1);
	}
	//Open file and counter number of lines.
	fp = fopen(argv[1],"r");
	//Check if file was opened.
	if(!fp){
		cout << "IO/Error, Faild to open file:" << endl << argv[1] << endl;
		exit(1);
	}
	while(fgets(line,255,fp) != NULL){
		//Keep line count
		i++;
	}
	//Rewind back to start of file
	rewind(fp);
	//Convert the number of lines to ascii
	itoa(i,sLen,10);
	//Get the length of the ascii string above
	len = strlen(sLen);
	//Retset i we use this again.
	i = 1;
	//While not end of file read in lines
	while(fgets(line,255,fp) != NULL){
		//Fill the left side of the line with line count
		cout.fill('0');
		//Set length of padding
		cout.width(len);
		//Output line index
		cout << i << " ";
		//Output line
		cout << line;
		//Keep line index going till no more lines
		i++;
	}
	//Close file
	fclose(fp);
	//Clear char arrays.
	memset(line,0,sizeof(line));
	memset(sLen,0,sizeof(sLen));
	//Ret
 return 0; 
} 


Other 50 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.