Zako
Zako

Reputation: 65

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

I'm having a problem with a program (part of a program). To proceed any further I need to somehow read a line of a file but that must be a specific line. I'm really new to C and files...

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

Is there any 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);

Upvotes: 3

Views: 6510

Answers (1)

cnicutar
cnicutar

Reputation: 182639

How about:

  • Read characters from the file, one by one, using getc, until you encounter the required number of newlines minus 1
  • Read 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 */

Upvotes: 5

Related Questions