Print the last k lines of the file (C + + and Java implementations)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.