Write a C program to implement a command called ​displaycontent ​that takes a (text) file name as argument and display its contents. Report an appropriate message if the file does not exist or can’t be opened (i.e. the file doesn’t have read permission). You are to use ​open()​, ​read()​, ​write() ​and

Answer :

Answer:

/*

Student: Hugo Meza

Date: February 15, 2019

Description: This program mimic the cat command from Linux. Checks whether the source file

has the right permissions, and then writes in the console its content.

*/

#include <stdio.h>

#include <fcntl.h>

#include <unistd.h>

#include <errno.h>

int hasPermission(char *filepath){

int returnval;

// Check file existence

returnval = access (filepath, F_OK);

if(errno == ENOENT){

printf ("%s does not exist\n", filepath);

return 0;

}

else if (errno == EACCES){

printf ("%s is not accessible\n", filepath);

return 0;

}

// Check read access

returnval = access (filepath, R_OK);

if(errno == ENOENT){

printf ("%s does not have read access\n", filepath);

return 0;

}

else if (errno == EACCES){

printf ("%s is not accessible\n",filepath);

return 0;

}

// Check write access

returnval = access (filepath, W_OK);

if(errno == ENOENT){

printf ("%s does not have read access\n", filepath);

return 0;

}

else if (errno == EACCES){

printf ("%s is not accessible\n",filepath);

return 0;

}

return 1;

}

int main(int argc, char* argv[]){

if(!argv[1]){

printf("Error. Specify file to open\n");

return 0;

}

int fd;

char *fp = argv[1], content[fd];

if(hasPermission(fp) == 0)

return 1;

fd = open(fp, O_RDONLY);

int bytes = read(fd,content,sizeof(content)-1);

write(1, content, bytes);

close(fd);

return 0;

}

Explanation:

Other Questions