How avoid blank line at end of file

Hello,

I have a small program that I want to use to delete all lines in a file after a certain line. It works fine except it puts a newline (I assume an '\n') at the end, whereas I don't want any blank line at the end. I thought the way it is written would avoid this, but apparently not. Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using namespace std;
#include <cstdlib> 
#include <iostream> 
#include <fstream> 
#include <iomanip>  
#include <stdio.h> 
#include <string>
#include <string.h>

int main() {

	int i, keep;
	string line, name;
	cout << "Filename: ";
	cin >> name;
	ifstream in; 
	in.open(name.c_str());
	getline(in, line);
	cout << "First line: " << line  << endl;
	cout << "Lines to keep: ";
	cin >> keep;
	ofstream out;
	out.open("linetemp.dat");
	for(i=0;i<keep-1;i++) {
		out << line << endl;
		getline(in, line);
	}
	out << line;
	remove(name.c_str());
	rename("linetemp.dat", name.c_str());
	out.close();
	in.close();
	return 0;
}
How do you know there is a new line character at the end? Have you opened the file in a hex editor? Many text editors automatically appends a new line character at the end if one is missing.
Topic archived. No new replies allowed.