打印文件的最后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
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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。