-1

I have a text file with one number in each line.

I want to read a specific number of lines from this file , lets say the first 20, what is the way to do it?

I have the following piece of code.

FILE *ft;
ft=fopen(filename,"r");
for(int k=1; k<Nt+1; k=k+1) 
{
    fscanf(ft,"%lf\n",&curve3[k]);
    printf("%lf\n",curve2[k]);
}

EDIT: I changed my code to

FILE *ft;
ft=fopen(filename,"r");
int k=1;

while(!feof(ft))
{
    if(k<=Nt)
    {
        fscanf(ft,"%lf\n",&curve2[k]);
        //printf("%lf\n",curve2[k]);
    } 
    k=k+1;
}

It still doesn't seem to work.

kdopen
  • 8,032
  • 7
  • 44
  • 52

1 Answers1

0

With this code you can read a file line by line and hence read a specific line from the text file. So, you can modify the code.

lineNumber = x;

static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
    char line[256]; /* or other suitable maximum line size */
    while (fgets(line, sizeof line, file) != NULL) /* read a line */
    {
        if (count == lineNumber)
        {
            //use line or in a function return it
            //in case of a return first close the file with "fclose(file);"
        }
        else
        {
            count++;
        }
    }
    fclose(file);
}
else
{
    //file doesn't exist
}