c - 在C中扫描文件中的特定行

标签 c file structure

我有一个简单的程序,它从文件中获取值并将其显示在屏幕上。但是,我的结构似乎不起作用,因为它总是插入文件中的第一个值。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

void insert(void);

int lineNum;

FILE *fPresDr;

struct store09
{
    char defPsDr[16];
}stock09[16];


int main()
{
    printf("Type the line number you want to view");
    scanf("%d",&lineNum);
    insert();
    printf("\n\nThe value in file is: %s",stock09[lineNum].defPsDr);
    getch();
}


void insert(void)
{
     fPresDr=fopen("TIRpresD.txt","r");
     fscanf(fPresDr,"%127[^\n]%*c",stock09[lineNum].defPsDr);
     fclose(fPresDr);
}

示例文件:

two
seven
four
eleven

输入:“3”。预期输出:“四”。实际输出:“两个”

最佳答案

使用 fscanf 似乎不仅有点过分,而且还依赖于平台。为什么不调用 readline 足够多次来获取您想要的行呢?

关于c - 在C中扫描文件中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26466891/

相关文章:

java - 如何减少查找数字阶乘的最后一个非零数字的运行时间?

python - 对文件内容进行排序

android - 如何将来自服务器的 base64 json 文件保存在移动外部存储中?

c - fopen() 在调用之前导致段错误

c - nlopt 中的固定区间约束

c - 数组的动态结构、段错误

go - 我可以限制包在 Golang 中有一些功能吗?

c - 比较结构以便对列表进行排序的函数

c - 将 char 数组初始化为 NULL 奇怪的行为

c - 查找文本文件中某行的特定信息