Einārs Ozols
Einārs Ozols

Reputation: 155

Structures and files in c

I have some problem. I have made text file studenti.txt with content like this:

  1. Gatis Lietnieks 15.06.1993 v
  2. Vizma Kalesnica 20.08.1991 s
  3. Katrina Sabone 06.12.1992 s
  4. Haralds Burkovskis 01.02.1989 v
  5. Jezups Martinovs 02.05.1990 v
  6. Vizma Zigurde 16.09.1988 s
  7. Stasija Balode 12.12.1993 s
  8. Jānis Bērziņš 13.03.1992 v
  9. Zigurds Ritms 16.05.1991 v
  10. Pauls Zirdzins 12.11.1989 v
  11. Zane Skarbule 28.12.19990 s
  12. Aiga Bulle 11.08.1993 s
  13. Andrejs Fomkins 11.06.1989 v
  14. Maikls Dzordans 08.01.1988 v

And i want to read this file and print the content of the file in c program. My code is like this:

 #include <stdio.h>
 #include <conio.h>
 #include <string.h>
 #include <windows.h>
 #define N 16
 int main()
 {
 FILE *fails_st;

 struct date
 { int da_year;
   int da_month;
   int da_day;
 };

 struct studenti
 {
 int Nr;
 char name[25];
 char surname[25];
 struct date dzd;
 char dzimums[10]; 
 } students[N];

 int i, j;
 system("cls");

 fails_st = fopen("studenti.txt", "r");
 for(i=0; i<N; i++)
 {
 fscanf(fails_st, "%d", students[i].Nr);
 fgets(students[i].name, strlen(students[i].name)+1, fails_st);
 fgets(students[i].surname, strlen(students[i].surname)+1, fails_st);
 fscanf(fails_st, "%d", students[i].dzd.da_day);
 fscanf(fails_st, "%d", students[i].dzd.da_month);
 fscanf(fails_st, "%d", students[i].dzd.da_year);
 fgets(students[i].dzimums, strlen(students[i].dzimums)+1, fails_st);
 }
 fclose(fails_st);
 system("cls");
 printf("Student list\n");
 for(i=0; i<N; i++)
 printf("%4d%15s%15s%d%d%d%%4s\n", students[i].Nr, 
 students[i].name, students[i].surname, 
 students[i].dzd.da_day,students[i].dzd.da_month,students[i].dzd.da_year,students[i].dzimums);
 getch();
 return 0;
 }

But when i run it program just stops "myfilename.exe has stopped working..........." And i am wondering where is the mistake in my code.

Upvotes: 1

Views: 106

Answers (1)

unwind
unwind

Reputation: 399753

Please read the documentation for fscanf(), you are using it wrong. You must pass the address of where you expect fscanf() to store the data it converts: how else do you expect it to be able to write in your variable?

In other words, this:

fscanf(fails_st, "%d", students[i].Nr);

should be:

fscanf(fails_st, "%d", &students[i].Nr);

where & is C's "address of"-operator, which evaluates to the address of the expression.

Another problem is that you use strlen() on uninitialized strings, that's not valid. You meant:

fgets(students[i].name, sizeof students[i].name, fails_st);

Also remember that I/O calls can fail, you really should check return values.

Upvotes: 5

Related Questions