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.

Recommended Answers

All 6 Replies

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.

Show the code you have for reading the entire content and I'll go from there.

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;

}

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

Thank you so much

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.