user3227362
user3227362

Reputation: 71

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

Now i have been given a program to solve this, however it uses the function getline() , which doesn't complie on 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()

Thanks

Edit: I also don't want to download software to make this work

Upvotes: 0

Views: 17808

Answers (3)

vinayawsm
vinayawsm

Reputation: 865

you can add this part in your program instead of your do-while loop. You will be using fscanf() whose arguments are the file pointer, specifier of data type and the variable you want to store.

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

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

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

Upvotes: 0

BLUEPIXY
BLUEPIXY

Reputation: 40145

use fgets instead of 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;
}

Upvotes: 2

abdolah
abdolah

Reputation: 564

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

Upvotes: 1

Related Questions