How to read a specific line in a text file in C (integers)

I have a problem with a program (part of a program). To continue, I need to somehow read a line of the file, but it has to be a specific line. I'm really new to C and files ...

What I'm trying to do is ask the user to enter a specific string they want to read and then display it for them. At the moment, when I try to print text from line, it gives me text from line 1 only. Note that by text I mean integers since the file is 55 integers in one column. It looks like this: 12 18 54 16 21 64 .....

Is there a way to achieve what I need?

#include <stdio.h>

FILE *file;

char name[15];
int line;
int text;

file = fopen("veryimportantfile.txt","r");
if(file==NULL)
{
    printf("Failed to open");
    exit(1);
}


printf("Your name: ");
scanf("%s",&name);
printf("\Enter the line number you want to read: ");
scanf("%d",&line);


fscanf(pFile, "%d", &line);
printf("The text from your line is: %d",line);

      

+3


source to share


1 answer


What about:

  • Read characters from file one by one using getc

    until you meet the required number of new lines minus 1
  • Reading integers using a loop and fscanf("%d", ...)



Something like:

int ch, newlines = 0;
while ((ch = getc(fp)) != EOF) {
    if (ch == '\n') {
        newlines++;
        if (newlines == line - 1)
            break;
    }
}

if (newlines != line - 1)
    /* Error, not enough lines. */

/* fscanf loop */

      

+5


source







All Articles