gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:13:15 26 4
gpt4 key购买 nike

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

我想做的是要求用户输入他们想要阅读的特定行,然后将其显示给他们。目前,当我尝试打印该行的文本时,它只给我第 1 行的文本。请注意,我所说的文本是指整数,因为该文件在一列中包含 55 个整数。所以它看起来像这样:121854162164.....

有什么办法可以实现我所需要的吗?

#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);

最佳答案

怎么样:

  • 使用 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 */

关于c - 如何在 C 中读取文本文件中的特定行(整数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14885202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com