Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The following code addresses multiple problems - not only does it make sure that strings are "safely" copied (using <code>strncpy</code>, and terminating the string with a <code>'\0'</code>), but it also makes sure you don't create a second copy of all the data in memory (not a problem with a toy example, but why start with bad habits).</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; struct students //Defining structure for students { int id; //Students ID Number char name[30]; //Students Name int age; //Students Age char dept[4]; //Studets Department int grade; //Students Grade }; int main() { struct students list[20]; FILE *f; char line[30]; char **temp = NULL; int num_righ = 0; int id5; int age5; int grade5; int i, k=0; char *newLine; f = fopen("records.txt", "r"); int s = 0; // this is the "state" counter - it goes from 0 to 4, then back to 0 while(fgets(line, sizeof (line), f) != NULL) { newLine = strchr(line, '\n'); if(newLine) *newLine='\0'; // terminate string on the newline. switch(s) { case 0: list[k].id = atoi(line); break; case 1: strncpy(list[k].name, line, 30); list[k].name[29]='\0'; // make sure it is terminated break; case 2: list[k].age = atoi(line); break; case 3: strncpy(list[k].dept, line, 3); list[k].dept[3] = '\0'; // make sure it is terminated break; case 4: list[k].grade = atoi(line); break; } s++; if (s == 5) { s = 0; k++; // if it's 5, go back to zero and start reading next structure } } fclose(f); for (i = 0; i &lt; k; i++) { printf("id: %d\n", list[i].id); printf("name: %s", list[i].name); printf("age: %d\n", list[i].age); printf("dept: %s\n", list[i].dept); printf("grade: %d\n\n", list[i].grade); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload