Reputation: 155
I have some problem. I have made text file studenti.txt with content like this:
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
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