Late submissions not accepted. Solution available after the due date. Submit you
ID: 3853929 • Letter: L
Question
Explanation / Answer
NOTE: Execution of the code is also available at link https://pasteboard.co/Gzj72ug.png. Let me know if you face any issues and i will revert back within 24 hours
Code:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define BUF_SIZE 8192
int main(int argc, char *argv[])
{
/* variable declaration */
int fd, i = 0, j = 0, k;
char buffer[BUF_SIZE];
char temp[100];
/* checking if the arguments passed correctly */
if(argc != 2){
printf("Usage: %s FILE ", argv[0]);
exit(0);
}
/* opening a file in read mode */
fd = open(argv[1], O_RDONLY);
/* if fd is -1 which means file does not exist or not referenced from correct path */
if(fd == -1){
printf("Couldn't open file %s: No such file or directory ", argv[1]);
exit(0);
}
/* file exists so reading the file */
else{
/* reading the entire file in buffer array */
read(fd, &buffer, BUF_SIZE);
/* iterating 10 times */
for(i = 0 ; i < 10; i++){
/* iterating through buffer variable and storing in temp array each line */
for(k = 0;buffer[j] != ' ' && buffer[j] != -1; j++)
temp[k++]=buffer[j];
if(buffer[j] != -1){
temp[k] = '';
printf("%s ", temp);
}
else
break;
j++;
}
}
/* closing the file */
close(fd);
return 0;
}
Execution and output:
Unix Terminal> ./mh check
safkljfs
f;lkjasl;fjs;f
1
saf;asfsal;kfj
Unix Terminal> ./mh textfile.txt
this
is
a
test
of
the
program
and
it
works
Unix Terminal> ./mh test
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
Unix Terminal> ./mh testinggg
Couldn't open file testinggg: No such file or directory
Unix Terminal> ./mh
Usage: ./mh FILE
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.