简体   繁体   English

C编程读取文本文件的特定行

[英]C programming Reading a specific line of a text file

So i've been given an exercise to work on: Have the user input a number and the program will display the line of text associated with that line for example 所以我已经进行了一项练习:让用户输入一个数字,程序将显示与该行相关的文本行,例如

Password 
abcdefg 
Star_wars 
jedi
Weapon 
Planet 
long 
nail 
car 
fast 
cover 
machine 
My_little
Alone
Love
Ghast

Input 3: Output: Star_wars 输入3:输出:Star_wars

Now i have been given a program to solve this, however it uses the function getline() , which doesn't complie on DEV C++. 现在我已经得到了一个程序来解决这个问题,但是它使用了函数getline() ,它不能编译DEV C ++。

#include <stdio.h>

int main(void)
{
int end = 1, bytes = 512, loop = 0, line = 0;
char *str = NULL;
FILE *fd = fopen("Student passwords.txt", "r");
if (fd == NULL) {
    printf("Failed to open file\n");
    return -1;
}
    printf("Enter the line number to read : ");
    scanf("%d", &line);

do {
    getline(&str, &bytes, fd);
    loop++;
    if (loop == line)
        end = 0;
}while(end);

printf("\nLine-%d: %s\n", line, str);
    fclose(fd);
}

All i need is to know how to do this, in a simple program without the use of getline() 我需要的是在一个简单的程序中知道如何做到这一点,而不使用getline()

Thanks 谢谢

Edit: I also don't want to download software to make this work 编辑:我也不想下载软件来使这项工作

You have wrote: 你写道:

char *str = NULL;

and you used it without initializing: 你没有初始化就使用它:

getline(&str, &bytes, fd);

first you must initialize it: 首先你必须初始化它:

char *str=(char*)malloc(SIZEOFSTR);

use fgets instead of getline. 使用fgets而不是getline。

#include <stdio.h>

int main(void){
    int end, loop, line;
    char str[512];
    FILE *fd = fopen("data.txt", "r");
    if (fd == NULL) {
        printf("Failed to open file\n");
        return -1;
    }
    printf("Enter the line number to read : ");
    scanf("%d", &line);

    for(end = loop = 0;loop<line;++loop){
        if(0==fgets(str, sizeof(str), fd)){//include '\n'
            end = 1;//can't input (EOF)
            break;
        }
    }
    if(!end)
        printf("\nLine-%d: %s\n", line, str);
    fclose(fd);

    return 0;
}

you can add this part in your program instead of your do-while loop. 你可以在你的程序中添加这个部分,而不是你的do-while循环。 You will be using fscanf() whose arguments are the file pointer, specifier of data type and the variable you want to store. 您将使用fscanf(),其参数是文件指针,数据类型的说明符和要存储的变量。

printf("Enter the line number to read : ");
scanf("%d", &line);

while(line--) {
    fscanf(fd,"%s",str);
}

printf("\nLine-%d:%s\n",line,str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM