Title, the contents of file.txt are as follows:
1234567891011121314151617181920
C + + implementation:
#include <iostream> #include <fstream> #include <string>using namespace std;//const unsigned int k = 5;# Define K 5void 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");p rintlastklines (Fin); Fin.close (); return 0;}
Operation Result:
1617181920
Java implementations:
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]);}}}
Operation Result:
1617181920
Note: In the Java implementation, the file.txt file needs to be placed at the root of the project. Otherwise the return of the FileNotFound exception.
Print the last k lines of the file (C + + and Java implementations)