Simple C Program to Retrieve details From a text file (student records)

Reading Time: 5 minutes

Today we are going to continue on with our simple database program we started in https://www.rukbook.com/c-program-to-a-student-simple-text-file-database/ which is a very simple method with C programming to store data. We are just using a .txt file as our backend. It’s not the most secure database you’ll ever find but should be good enough for you to get a glimpse of file writing and reading with C. So, let’s get on to our simple C program to retrieve details from the text file that we saved earlier.

Full Code

Here’s the full source code for this project.

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

int main() {
    char col_label[20];
    int col_iteration_count = 0;
    const char s[2] = ",";
    char *token;
    char user_input_id[50];

    while(1) {
        printf("\n\nEnter zero to exit the program");
        printf("\nEnter Student ID to retrieve details : ");
        scanf("%s", &user_input_id);

        //Enter "0" to exit the program.
        if (!strcmp(user_input_id, "0")){
            break;
        }

        const char filename[] = "../student_details.txt";
        FILE *file = fopen(filename, "r");
        if (file != NULL) {
            char line[128]; /* or other suitable maximum line size */
            while (fgets(line, sizeof line, file) != NULL) /* read a line */
            {
                //set count to zero each row,
                col_iteration_count = 0;

                /*get first token (student_id)*/
                token = strtok(line, s);

                //if both strings are same,
                if (!strcmp(token, user_input_id)) {
                    /* walk through other tokens */
                    while (token != NULL) {
                        switch (col_iteration_count) {
                            case 0:
                                strcpy(col_label, "ID");
                                break;
                            case 1:
                                strcpy(col_label, "Name");
                                break;
                            case 2:
                                strcpy(col_label, "Gender");
                                break;
                            case 3:
                                strcpy(col_label, "Age");
                                break;
                            case 4:
                                strcpy(col_label, "Phone Number");
                                break;
                            default:
                                printf("ERROR");
                        }
                        printf("\nStudent %s : %s", col_label, token);
                        col_iteration_count++;
                        token = strtok(NULL, s);
                    }
                }
            }
            fclose(file);
        } else {
            perror(filename); /* why didn't the file open? */
        }
    }
    return 0;
}

What are we doing here again?

Here’s what we are going to achieve in this tutorial,

  • Enter the id of a particular student to retrieve the details of.
  • Display those details on the console
  • Repeat this procedure until user chooses to exit the program.

What are the pre-requisites?

Here’s what we need to continue with this tutorial,

  • Placing a copy of that student_details.txt file in the outer folder to the folder containing the .exe (executable) of our program.

let’s explore the lines

Lines 1 and 2
#include <stdio.h>
#include <string.h>

These are the preprocessor directives that we’ve used.

The stdio.h file contains library functions such as printf() and scanf(). So in order to use those functions, we need to include that file in our program by using #include directive.

The string.h file contains library functions such as strcpy(). So in order to use those functions, we need to include that file in our program by using #include directive.

Lines 5 to 9
char col_label[20];
int col_iteration_count = 0;
const char s[2] = ",";
char *token;
char user_input_id[50];

These lines contain the variable declarations.

col_label is a character array variable of size 20 characters. Since the last character of a character array is the termination character \0” (without quotes), we can store 19 real characters in the col_label character array variable.

col_iteration_count is a normal integer variable that has been initialized to the value zero (0).

Lines 17 to 19
if (!strcmp(user_input_id, "0")){
    break;
}

Here we compare the value of variable user_input_id to check whether if it is equal to zero (0). If the values are equal, then the expression strcmp(user_input_id, “0”) returns 0 (logical false). I know, it seems a little counterintuitive. But, the ! symbol inverses that expressions’ evaluation.

Ultimately, the program flow will enter inside of this if expression if the value of user_input_id variable is 0.

The break statement will terminate the while(1) loop and thereby the whole program.

Line 21
const char filename[] = "../student_details.txt";

This line assigns the path and name of the text file that we are going to retrieve details from, to the character array variable filename.

The const keyword is used to say that this variable is a constant and that the value of the variable filename cannot be changed after this line.

Line 22
FILE *file = fopen(filename, "r");

In this line, we create a pointer of type FILE named file. We can later use this type to do file operations such as open, read data from and close a file, etc. (Pointers will be explained in a later article).

The r in within the parenthesis is to say that we are going to open the open for reading purposes only.

Line 24
char line[128];

Here we create a character array variable named line. We use this variable to store each line in our text file temporarily.

Line 25
while (fgets(line, sizeof line, file) != NULL)

Here we read the text file. One iteration of this while loop reads one line of the text file.

During each iteration, the read line is set to the variable line which we created earlier.

Lines 28 and 57
col_iteration_count = 0;
col_iteration_count++;

This col_iteration_count variable is used to traverse through the different fields in each row. For example, when value of this variable is 0, the first column of the current row is considered. When its value is 1, the second column of current row is considered etc.

This fact would be clear if we think the values stored (separated by commas) as a table.

Line 31
token = strtok(line, s);

Now inside the while loop, during each iteration, this line gets the first token (first comma-separated value) in the text file line, and set to the variable token.

Line 34
if (!strcmp(token, user_input_id)) {

Here we are checking whether the user input Id matches an id value stored in the text file.

‍The switch statement which follows is used to retrieve the other details relevant to the student whose Id was entered.

Line 62
fclose(file);

This is used to close the text file we opened. Although this is not essential, it is a good practice.

Line 64
perror(filename); /* why didn't the file open? */

This is used to print an Error the console if unable to open the particular text file. For example, if the text file is not available in the folder, this error is shown.

Line 67
return 0;

As in any C program, this line is there to print 0 to the console, to make sure the program executed successfully without any errors.

Conclusion

So that’s our simple C program to retrieve details from a text file, by entering the id of a student.

Special thanks to Wanuja, at https://www.linkedin.com/in/wanujaranasinghe/ for helping with the proof reading of this article.

If this article is hard for you, I suggest you checkout this article which would explain some simple things not covered in here. If you feel more lines should be explained in this article, please leave a comment below or contact me.

3.8 4 votes
Article Rating

Leave a comment. We love your feedback.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x