I have a file storing data of students in the following order:
id (space) name (space) address
Below is the content of the file:
10 john manchester
11 sam springfield
12 samuel glasgow
Each data is stored in a newline.
I want to search the student with id 10 and display his/her details using the lseek command, however I'm not to complete the task. Any help is appreciated.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
void main() {
char line[50] = "";
char id[2] = "";
ssize_t fd = open("file.dat", O_RDONLY);
while(read(fd,line,sizeof(line))>0){
if (id[0] == '1' && id[1] == '0'){
printf("%s\n",line);
}
lseek(fd, 1 ,SEEK_CUR);
}
close(fd);
Use the right tools for the task. Hammer for nails, Screwdriver for screws.
lseekis not the right tool here, sincelseekis for repositioning the file offset (which you do not have yet, you are looking for a specific position, when found, then you don't have a need for repositioning the file offset, since you are already there).Ask yourself,
What is your task:
What do you have:
Your dataset is separated by a newline, and the id is the first field of that row. The keywords here are 'newline' and 'first field'.
The right procedure here would be:
fgets)strcmp)Example: