首页 > 代码库 > 打印文件的最后K行(C++和Java实现)

打印文件的最后K行(C++和Java实现)

如题,file.txt的内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

C++实现:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

//const unsigned int k = 5;
#define k 5

void printLastKLines(ifstream &fin){
	string line[k];
	int lines = 0;
	string tmp;
	while(getline(fin, tmp)) {
		line[lines % k] = tmp;
		lines++;
	}
	int start, cnt;
	if(lines < k) {
		start = 0;
		cnt = lines;
	} else {
		start = lines;
		cnt = k;
	}
	for(int i = 0; i < cnt; i++) {
		cout << line[(start + i) % k] <<endl;
	}
}


int main()
{
	ifstream fin("file.txt");
	printLastKLines(fin);
	fin.close();
	return 0;
}

运行结果:

16
17
18
19
20


Java实现:

package com.leetcode;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class PrintLastKLines {
	public static void main(String[] args) throws IOException {
		int k = 5;
		printLastKLine(k);
	}
	
	public static void printLastKLine(int k) throws IOException{
		FileReader f = new FileReader("file.txt");
		BufferedReader br = new BufferedReader(f);
		String[] line = new String[k];
		String tmp;
		int lines = 0;
		while((tmp = br.readLine()) != null){
			line[lines % k] = tmp;
			lines++;
		}
		int start, cnt;
		if(lines < k){
			start = 0;
			cnt = lines;
		} else{
			start = lines;
			cnt = k;
		}
		for(int i = 0; i < cnt; i++){
			System.out.println(line[(start + i) % k]);
		}
	}
}

运行结果:

16
17
18
19
20
注意:在Java实现中,file.txt文件需要放置在项目的根目录处。否则回报FileNotFound的异常。


打印文件的最后K行(C++和Java实现)