hey people
i have written a program to demonstrate the use of fseek() function on a file.
the program creates a file student.txt in writing mode and the user enters the name and roll number of four students which are stored on the file.
after this the file is opened in reading mode and the user enters the record number which he needs to see.
then using the fseek() function the program displays only that record of the file.
the program is working fine but when i open the text file created, its contents are pretty messed up.
here is my code
Code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct student
{
char name[30];
char roll[12];
}st;
void main()
{
FILE *fp;
int i=0;
clrscr();
fp=fopen("D:\student.txt","w");
if(fp==NULL)
{
printf("\nError opening file...");
exit(0);
}
for(i=0;i<=3;i++)
{
printf("\nenter name : ");
scanf("%s",&st.name);
printf("\nenter roll : ");
scanf("%s",&st.roll);
fwrite(&st,sizeof(struct student),1,fp);
}
fclose(fp);
int x;
printf("\nEnter record number : ");
scanf("%d",&x);
fp=fopen("D:\student.txt","r");
if(fp==NULL)
{
printf("\nerror opening file...");
exit(0);
}
fseek(fp,(x-1)*sizeof(struct student),SEEK_SET);
if(fread(&st,sizeof(struct student),1,fp)==1)
{
printf("\nName = ");
printf("%s\n",st.name);
printf("Roll = ");
printf("%s",st.roll);
}
fclose(fp);
}
My output is....
Code:
enter name : abhilash
enter roll : 123
enter name : arati
enter roll : 456
enter name : jayajeet
enter roll : 789
enter name : hyder
enter roll : 135
Enter record number : 3
name= jayajeet
roll= 789
the program works fine with any number entered between 1 and 4.
but when i open the file created in notepad its contents are all messed up.
here is the content of the file student.txt
Code:
abhilash 123 arati sh 456 jayajeet 789 hyder et 135
the entries made in the file have random letters in a weird pattern.
i want to give it a traditional database look like the following one.
Code:
abhilash 123
arati 456
jayajeet 789
hyder 135
this i can do easily with fprintf() function but then the fseek() function does not work.
this program is gonna be part of my project. any suggestion ???