Thread: Program to view 10 lines of file.

  1. #1
    Registered User
    Join Date
    Apr 2018

    Question Program to view 10 lines of file.

    I'm having trouble writing a program that counts ten lines and displays only the characters from those lines. I want the program to read the characters one at a time from the file. I have here the code I've managed to write so far. Any help would be greatly appreciated.

    #define FNLEN 100
    int main(void)
        FILE *input;
        char infilename[FNLEN];
        char character;
        int line_count;
        printf("Enter name of text three you wish to preview: ");
        scanf("%s", infilename);
        input = fopen(infilename, "r");
        while ((input = fopen(infilename, "r"))) == NULL)
            printf("%s is an invalid name.\n", infilename);
            printf("Please enter valid file name. ");
            scanf("%s", infilename);
        while (fscanf(input, "%c", &character) != EOF)

  2. #2
    Registered User
    Join Date
    Apr 2018
    I'd use fgets to get the filename or better just pass it as a command line argument. Also you don't really need fscanf to read a file character by character, fgetc is way better.
    Something like this should do the trick:

        #define N_LINES 10
        FILE *f;
        int c;
        size_t n_spaces;
        n_spaces = 0;
        while (EOF != (c = fgetc(f)) && (N_LINES + 1) != n_spaces)
            if('\n' == c)
            if(N_LINES != n_spaces)

  3. #3
    Registered User
    Join Date
    May 2012
    Arizona, USA
    Does the advice on your other thread help at all?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 04-24-2018, 01:20 PM
  2. Replies: 4
    Last Post: 11-27-2013, 12:24 PM
  3. 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
  4. 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
  5. view source of html file
    By bballzone in forum C++ Programming
    Replies: 17
    Last Post: 09-04-2004, 04:23 PM

Tags for this Thread