如何用C(整数)读取文本文件中的特定行

Zak*_*ako 3 c file scanf

我遇到程序问题(程序的一部分).为了进一步继续,我需要以某种方式读取文件的一行,但必须是一个特定的行.我是C和文件的新手......

我想要做的是要求用户输入他们想要阅读的特定行,然后将其显示给他们.目前,当我尝试从行中打印文本时,它只给出了第1行的文本.请注意,通过文本我的意思是整数,因为该文件由一列中的55个整数组成.所以它看起来像这样:12 18 54 16 21 64 .....

有没有办法达到我的需要?

#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);
Run Code Online (Sandbox Code Playgroud)

cni*_*tar 5

怎么样:

  • 使用逐个读取文件中的字符getc,直到遇到所需数量的换行减去1
  • 使用循环读取整数和 fscanf("%d", ...)

就像是:

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 */
Run Code Online (Sandbox Code Playgroud)