I need to set an integer n
using an argument -n
that will be set as the amount of characters to print from the end of a given .txt
file. This needs to be done without the <stdio.h>
library as it is a homework piece about system calls.
I have a program that is able to accept the argument -n
and prints the amount of characters as specified by the user. It however prints an unreadable list of characters and NULLS
after the required output and causes my terminal to malfunction.
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
//declaration of variables
char buf[1000];
int fd;
int n;
//initialising n to zero
n = 0;
//checking if the program run call is greater than one argument
if(argc > 1){
//if the second argument is equal to '-n' then take the 3rd argument (the int) and put it into n using stroll (string to long)
if(!strncmp(argv[1], "-n", 2)){
n = atoi(argv[2]);
}
//if n has no set value from -n, set it to 200
if(n == 0){
n = 200;}
// open the file for read only
fd = open("logfile.txt", O_RDONLY);
//Check if it can open and subsequent error handling
if(fd == -1){
char err[] = "Could not open the file";
write(STDERR_FILENO, err, sizeof(err)-1);
exit(1);
}
//use lseek to place pointer n characters from the end of file and then use read to write it to the buffer
lseek(fd, (n-(2*n)), SEEK_END);
read(fd, buf, n);
//write out to the standard output
write(STDOUT_FILENO, buf, sizeof(buf)-1);
//close the file fd and exit normally with code 0
close(fd);
exit(0);
return(0);
}