Show 10 students data ( student id, father's name, phone number, mail id) in a file and write a C program to display the student's data whose id is given by a user through the keyboard.

Please help me out in solving this program. I know how to read data from the file, but i don't know how to read selected data from the file.

Edited 3 Years Ago by lalitha2294

That selection is done in the application itself, right? So just ask for a student ID and display the data of the user that has that ID. (You mentioned you can read the data just fine, so looking it up should be trivial)

Can you please explain with a code?? I know how to read the whole content of the file, but not a part of it.

Edited 3 Years Ago by lalitha2294

If suppose I have the students data in a 'string' text document like this

Student id Name Father's Name Phone no. Mail id

11011501 Tom Tommy 1234567 Tom@gmail.com
11011502 Sam Sammy 2345678 Sam@gmail.com

and so on.

This program is to read the whole content of that file. My question is if I ask the user to enter the student's id during runtime , the I should match that student's id with the id in my text document and dispaly that student's details.

#include<stdio.h>

int main(){

    char str[70];

    FILE *p;

    if((p=fopen("string.txt","r"))==NULL){

        printf("\nUnable t open file string.txt");

        exit(1);

    }

    while(fgets(str,70,p)!=NULL)

        puts(str);

    fclose(p);

    return 0;

}

Edited 3 Years Ago by deceptikon: Fixed indentation in code block

You need to break the line up such that the ID can be compared. If subsequent details also need to be treated separately then strcmp() and strtok() come to mind as a viable first attempt:

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

#define WHITESPACE " \t\n\r\f\v"

int main(void)
{
    FILE *in = fopen("test.txt", "r");

    if (in) {
        char id[70];

        fputs("Please enter a student ID: ", stdout);
        fflush(stdout);

        if (scanf("%69s", id) == 1) {
            char line[BUFSIZ];

            while (fgets(line, sizeof line, in)) {
                char *tok = strtok(line, WHITESPACE);

                if (strcmp(id, tok) == 0) {
                    /* Woot! Matched the ID, print the rest of the details */
                    printf("Found student ID [%s]:\n", id);

                    while (tok = strtok(NULL, WHITESPACE))
                        printf("\t'%s'\n", tok);
                }
            }
        }

        fclose(in);
    }

    return 0;
}
This article has been dead for over six months. Start a new discussion instead.