{"id":9194,"date":"2024-02-12T13:13:45","date_gmt":"2024-02-12T11:13:45","guid":{"rendered":"https:\/\/blue.pri.ee\/ttu\/?page_id=9194"},"modified":"2026-06-22T13:51:48","modified_gmt":"2026-06-22T11:51:48","slug":"reading-from-a-file-into-structure-array","status":"publish","type":"page","link":"https:\/\/blue.pri.ee\/ttu\/programming-ii\/code-samples\/reading-from-a-file-into-structure-array\/","title":{"rendered":"Reading from a file into structure array"},"content":{"rendered":"<p>This is a sample that will be written together in programming 2 in the class dedicated to structures.<\/p>\n<p>Data file format is\u00a0 <span class=\"lang:c highlight:0 decode:true crayon-inline\">&lt;name&gt; &lt;grade&gt;<\/span> , where the name can consist from up to 63 characters and be a single word. Grade must be an integer. Data fields are separated by spaces.<\/p>\n<p>Notice, that there is no guards for buffer overflow &#8211; if you enter 64 or more characters for the name, it will write beyond the bounds of the array and<strong> can cause data corruption or the program crashing.<\/strong><\/p>\n<pre class=\"toolbar:1 lang:c decode:true \">\/**\r\n * File:        struct_file.c\r\n * Author:      Risto Heinsar\r\n * Created:     10.01.2021\r\n * Last edit:   22.06.2026\r\n *\r\n * Description: Reads student data from a file into a struct array.\r\n *              Name of the file passed as first argument\r\n *\r\n *              Compile using --std=c99 or later.\r\n *\/\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n\r\n\/* 1 to enable printing debug statements, 0 to silence them *\/\r\n#define DEBUG             1\r\n\r\n\/* Predefined array limits *\/\r\n#define STR_MAX_LEN      64\r\n#define STUDENT_MAX_CNT  32\r\n\r\n\/* Options for command line args *\/\r\n#define ARGS_CNT          2\r\n\r\n#define ARGS_EXEC_NAME    0\r\n#define ARGS_FILE_NAME    1\r\n\r\nstruct Student\r\n{\r\n    char name[STR_MAX_LEN];\r\n    int grade;\r\n};\r\n\r\nint ReadData(char *fName, struct Student *students, int limit);\r\nvoid PrintData(struct Student *students, int cnt);\r\n\r\nint main(int argc, char **argv)\r\n{\r\n    \/* Check that argument was passed*\/\r\n    if (argc != ARGS_CNT)\r\n    {\r\n        fprintf(stderr, \"Usage: %s data_file\\n\", argv[ARGS_EXEC_NAME]);\r\n        return EXIT_FAILURE;\r\n    }\r\n\r\n    \/* Create struct array *\/\r\n    struct Student studentGrades[STUDENT_MAX_CNT];\r\n\r\n    \/* Read student data from file *\/\r\n    int studentCnt = ReadData(argv[ARGS_FILE_NAME], studentGrades, STUDENT_MAX_CNT);\r\n\r\n    \/* Print student data *\/\r\n    PrintData(studentGrades, studentCnt);\r\n\r\n    return EXIT_SUCCESS;\r\n}\r\n\r\n\/**\r\n * Description: Reads student data from a file into a struct array\r\n *\r\n * Parameters:  fileName - name of the file for input data\r\n *              students - struct array to store the data\r\n *              limit - maximum entries to read (struct array size)\r\n *\r\n * Return:      Number of studens read from the file\r\n *\/\r\nint ReadData(char *fileName, struct Student *students, int limit)\r\n{\r\n    FILE *fStudents = fopen(fileName, \"r\");\r\n    if (fStudents == NULL)\r\n    {\r\n        \/* Prints custom message + system error message from errno to stderr *\/\r\n        perror(\"Error! Cannot open input file\");\r\n\r\n        \/* Returns 0 students read from the file, allows program to continue *\/\r\n        return 0;\r\n    }\r\n\r\n    if (DEBUG) printf(\"Opened '%s' for reading student data\\n\", fileName);\r\n\r\n    \/* Counter for number of students from file *\/\r\n    int cnt = 0;\r\n\r\n    while (fscanf(fStudents, \"%s %d\",  students[cnt].name,\r\n                                      &amp;students[cnt].grade) == 2)\r\n    {\r\n        \/* Debugging print to check if input was read successfully *\/\r\n        if (DEBUG)\r\n            printf(\"DBG: from file (%d): %s %d\\n\", cnt + 1,\r\n                                                   students[cnt].name,\r\n                                                   students[cnt].grade);\r\n\r\n        \/* Student successfully read, increment student count *\/\r\n        cnt++;\r\n\r\n        \/* Avoid overflowing the array *\/\r\n        if (cnt &gt;= limit)\r\n        {\r\n            fprintf(stderr, \"Error! File is too long! Allowed max is %d!\\n\"\r\n                            \"Reading of the file has been stopped, continuing \"\r\n                            \"with a partial dataset!\\n\", limit);\r\n            break;\r\n        }\r\n    }\r\n\r\n    \/* Close the input file *\/\r\n    fclose(fStudents);\r\n\r\n    if (DEBUG) printf(\"DBG: Reading finished, got %d entries\\n\", cnt);\r\n\r\n    \/* Returns number of students read *\/\r\n    return cnt;\r\n}\r\n\r\n\/**\r\n * Description: Prints the Student array contents\r\n *\r\n * Parameters:  students - student data\r\n *              cnt - num of students in data array\r\n *\r\n * Return:      none\r\n *\/\r\nvoid PrintData(struct Student *students, int cnt)\r\n{\r\n    \/* Handling of no students *\/\r\n    if (cnt &lt;= 0)\r\n    {\r\n        fprintf(stderr, \"Error! Student db is empty!\\n\");\r\n        return;\r\n    }\r\n\r\n    printf(\"Student list contains %d students:\\n\", cnt);\r\n    for (int i = 0; i &lt; cnt; i++)\r\n    {\r\n        printf(\"%s %d\\n\", students[i].name, students[i].grade);\r\n    }\r\n}\r\n<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is a sample that will be written together in programming 2 in the class dedicated to structures. Data file format is\u00a0 &lt;name&gt; &lt;grade&gt; , where the name can consist from up to 63 characters and be a single word. Grade must be an integer. Data fields are separated by spaces. Notice, that there is &hellip; <a href=\"https:\/\/blue.pri.ee\/ttu\/programming-ii\/code-samples\/reading-from-a-file-into-structure-array\/\" class=\"more-link\">Loe edasi <span class=\"screen-reader-text\">Reading from a file into structure array<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":2361,"menu_order":4,"comment_status":"closed","ping_status":"closed","template":"page-templates\/code-width-wide.php","meta":{"footnotes":""},"class_list":["post-9194","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/pages\/9194","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/comments?post=9194"}],"version-history":[{"count":11,"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/pages\/9194\/revisions"}],"predecessor-version":[{"id":11513,"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/pages\/9194\/revisions\/11513"}],"up":[{"embeddable":true,"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/pages\/2361"}],"wp:attachment":[{"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/media?parent=9194"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}