To print a particular row/line when using files C programming

This post is related to manipulation of files in C.
If for eg, you have a list of records where each record is stored on a single line, this part can be helpful for you.
I used ‘lseek’ function to go to the start position of the required record and ‘\n’ to detect a new line. The solution:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

void main(){

char buf[100];
int fd;
fd = open (“myfile.dat”,O_RDONLY);
ssize_t n1= read (fd, buf, 100);
printf(“%s\n”, buf);

int chosenrecord;
printf(“Enter record number: \n”);
scanf(“%d”, &chosenrecord);

int count=1;
int rowfound=0;
int endpos;
int startpos=0; //defaut value 0 is used only for 1st record as no ‘\n’ is found
int j=0;

for(int i=0; i<= strlen(buf); i++){

if (buf[i]==’\n’){
startpos= i;
if (count == chosenrecord && rowfound==0){

for (j=i+1; j<= strlen(buf); j++){
if (buf[j]==’\n’){ //

int lengthrecord= endpos-startpos;
printf(“Start position of the record: %d\n”, startpos);
printf(“End position of the record:%d\n\n\n”, endpos);
lseek(fd, startpos, SEEK_SET); //SEEK_SET from beginning of file, save all data after the start position of record

printf(“Details of chosen record: \n”);
char bufrecord[100];
read(fd, bufrecord, lengthrecord); //print till end of record using record length

printf(“%s\n”, bufrecord);


close (fd);

Please Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s