Thread: C program to display only the first ten lines of text file.

  1. #1
    Registered User
    Join Date
    Apr 2018
    Posts
    2

    Question C program to display only the first ten lines of text file.

    I'm trying to write a program that reads a text file and displays the first ten lines. The way I'm trying to do this is with a loop that reads a character at a time from a file and within that loop I'd like it to keep track of the number of times the input character is '\n' and increment a variable that counts the lines and when the line count reaches 10, it closes the file and exits the loop. I'm not exactly sure how to do that. I'd like some example to get an idea what to do.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Start with a program which prints the whole file.

    Then add to that, something which counts and prints the number of newlines seen.

    Then finally, something to exit the loop when that counter reaches 10.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. program that deletes same lines in a text file
    By ferronia in forum C Programming
    Replies: 3
    Last Post: 03-23-2013, 05:42 PM
  2. My program don't read all lines of a text file
    By Netcode in forum C Programming
    Replies: 5
    Last Post: 04-13-2012, 07:45 PM
  3. Replies: 4
    Last Post: 04-24-2010, 03:38 AM
  4. Best way to read lines out of a text file
    By movl0x1 in forum C Programming
    Replies: 9
    Last Post: 05-29-2007, 12:45 PM
  5. lines of a text file
    By face_master in forum C++ Programming
    Replies: 8
    Last Post: 11-06-2001, 07:09 AM

Tags for this Thread