The program asks the user for input of names, IDs, etc, of 2 students, writes the data to a file and reads the data back from the file.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(){
int fd, i = 0;
char name[20], id[10], dob[10], gender[7], status[10];
fd = open("file.dat", O_WRONLY|O_CREAT, S_IRWXU); //open file.dat for writing; if it does not exist, create it
for (i = 0; i < 2; i++){
//get input from user
printf("\nFor student %d\n", (i + 1));
printf("Enter name: ");
scanf("%[^\n]%*c", name); //%[^\n]%*c - read everything up to (excluding) new line character
printf("Enter ID: ");
scanf("%[^\n]%*c", id);
printf("Enter date of birth: ");
scanf("%[^\n]%*c", dob);
printf("Enter gender: ");
scanf("%[^\n]%*c", gender);
printf("Enter marital status: ");
scanf("%[^\n]%*c", status);
//write current student to file
write(fd, name, 20);
write(fd, id, 10);
write(fd, dob, 10);
write(fd, gender, 7);
write(fd, status, 10);
}
close(fd);
//display data from file
char buf[20];
fd = open("file.dat", O_RDONLY); //open file for reading
for (i = 0; i < 2; i++){
printf("\nFor student %d\n", (i + 1));
read(fd, buf, 20); //read name
printf("Name: %s\n", buf);
read(fd, buf, 10); //read id
printf("ID: %s\n", buf);
read(fd, buf, 10); //read date of birth
printf("Date of birth: %s\n", buf);
read(fd, buf, 7); //read gender
printf("Gender: %s\n", buf);
read(fd, buf, 10); //read marital status
printf("Marital status: %s\n", buf);
}
}
The input part:
For student 1
Enter name: Mary Jane Smith
Enter ID: 1
Enter date of birth: 09/09/1990
Enter gender: Female
Enter marital status: Single
For student 2
Enter name: John Doe Paul
Enter ID: 2
Enter date of birth: 08/08/1993
Enter gender: Male
Enter marital status: Married
The display part:
For student 1
Name: Mary Jane Smith
ID: 1
Date of birth: 09/09/1990Smith
Gender: Female
Marital status: Single
For student 2
Name: John Doe Paul
ID: 2
Date of birth: 08/08/1993aul
Gender: Male
Marital status: Married
Some part of the name gets added to the date of birth. Why is this so and how do I solve this, please?
I have read that scanf is not reliable but I am required to use scanf in the program.
read()doesn't nul-terminate. - EOF09/09/1990need 11 instead of 10.dob[10]-->dob[11]- BLUEPIXY