fprintf(stderr,"rush: Error opening history file\n");
exit(EXIT_FAILURE);
}
// normal bufsize is 1024, we serach for 1025 bytes for new line feed
intsearch_len=RL_BUFSIZE+1;
charsearch[search_len];
fseek(history_file,-search_len,SEEK_END);// go back 1025 characters from end of file
intcount=fread(search,1,search_len-1,history_file);// try to read 1025 characters from file, returning count number of bytes
search[count]='\0';
char*last_nlf=strrchr(search,'\n');// locate last occurence of \n in a searching string
if(last_nlf==NULL){
// no history
returnNULL;
}
if(direction==1){// up
cmd_count++;
}else{// down
if(cmd_count==0){
returnNULL;
}else{
cmd_count--;
}
}
for(inti=0;i<cmd_count;i++){
search[last_nlf-search]='\0';// terminate string earlier to find second last \n, search points to first char and last_nlf is last \n, difference is the index of \n
last_nlf=strrchr(search,'\n');// call strrchr 2 times to get second last new line feed in search string as every life is new line feed
// check if the first \n is the last \n we searching for, if yes it is first command
cmd_count--;
search[last_nlf-search]='\0';// terminate string earlier to find second last \n, search points to first char and last_nlf is last \n, difference is the index of \n