I practice the subject of files in c, and I am currently learning the basics, meaning I do not control all the functions built into the language, and in some commands, so if you can explain according to the basic commands and something complex I will thank you.
What the program does: Absorption of students' data (identity card, name, and telephone), and print each student's data in the file (each student information will be written in a new line)
What's my problem with the code: I wrote a function that prints out all the data in the file, if the user inserted more than one student, the function prints only the first line in the file and that is it.
When I used F10 I got to the loop while the first run printed out the details of the first student, and then the second run, the fscanf command returned a value (-1) and did not print out the details of the second student.
I would be happy to guide, and to correct.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct studnt
{
int id;
int number;
char *name;
}typedef s_studnt;
void print_studnt(FILE *q,char name_file[])
{
int id, number;
char str_name[20];
q=fopen(name_file, "r");
if (q == NULL)
{
printf("eror fac\n");
return;
}
printf("\n");
while (!feof(q))
{
fscanf(q, "%d %s %d", &id, str_name, &number); //at the next loop, fscanf return -1
printf("studnt name:%s\nthe id studnt:%d\ntelephon number:%d\n", str_name, id, number);
printf("\n");
}
fclose(q);
return;
}
int main()
{
int size, i, length;
char str[20], name_file[20];
FILE *q = NULL;
s_studnt *studnt = NULL;
printf("how much studnt you have:\n");
scanf("%d", &size);
studnt = (s_studnt*)malloc(size * sizeof(s_studnt));
if (studnt == NULL)
{
printf("eror 1\n");
return 0;
}
printf("enter file name:\n");
scanf("%s", name_file);
q = fopen(name_file, "w");
if (q == NULL)
{
printf("eror file\n");
return 0;
}
fclose(q);
for (i = 0; i < size; i++)
{
printf("enter studnt name:\n");
scanf("%s", str);
length = strlen(str);
studnt[i].name = (char*)malloc(length+1 * sizeof(char));
if (studnt[i].name == NULL)
{
printf("eror2\n");
return 0;
}
strcpy(studnt[i].name, str);
printf("enter the id studnt:\n");
scanf("%d", &studnt[i].id);
printf("enter your telephon number:\n");
scanf("%d", &studnt[i].number);
q = fopen(name_file, "a");
if (q == NULL)
{
printf("eror write\n");
return 0;
}
fprintf(q, "%d %s %d\n", studnt[i].id, studnt[i].name, studnt[i].number);
}
fclose(q);
print_studnt(q,name_file);
return 0;
}