Hi all, I'm pretty new to C, so apologies in advance, I am trying to write code that will allow me to input a line no and then display the text from that line from the corresponding file. I'm having a bit of a brain fart & can't work it out, any help would be much appreciated.

#include <stdio.h>
#include <stdlib.h>
#define MAX_CHARACTERS 81
main()
{

    FILE *fp_in;
        char one_line[MAX_CHARACTERS];
        int line_numbers=0;




        if ( (fp_in=fopen("file.txt","r"))==NULL)
        puts("Error in opening file.txt" );
    
        else
            {
            printf("\nChoose line to display: ");
            scanf("%d",&line_numbers);
            }


        while (fgets(one_line,MAX_CHARACTERS,fp_in )!=NULL )
        {

        printf("%s",one_line);
        }

fclose ( fp_in );
}
jephthah commented: properly formatted and code tagged. there is still hope! +7

Just put a line counter in your while loop.

Check out this daniweb thread on scanf because if it is used improperly you can definitely have problems (such as overrunning the bounds of your char array) among other things. You also might want to see Dave Sinkula's snippet on reading an integer from the user for a more thorough and less error prone way to get the input. Oh, and I found one more useful resource on Daniweb on reading in Strings and Numbers in C, also written by Dave Sinkula. I'm also giving myself a refresher this morning since its been at least 2 years since I've done any serious C programming and these damn functions are a pain...

:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.