I'm trying to implement a command called displaycontent that takes a text file name as argument and display its contents. I am to use open()
, read()
, write()
, and close()
system calls in Linux to do this. It should act somewhat like the UNIX cat
command for displaying file content.
Here is what I have so far:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd;
char content[fd];
errno = 0;
fd = open(argv[1], O_RDONLY);
if(fd < 0)
{
printf("File could not be opened.\n");
perror("open");
return 1;
}
else
{
read(fd, content, sizeof(content)-1);
write(1, content, sizeof(content)-1);
}
return 0;
}
I have a file named hello2.txt and in it, there's the text: hellooooooooooooooo
When I do ./displaycontent hello2.txt
, I get:
user@user-VirtualBox:~/Desktop/Csc332/csc332lab$ ./displaycontent hello2.txt
hellooooooooooooooo
����>k���[`�s�b��user@user-VirtualBox:~/Desktop/Csc332/csc332lab$
There are strange symbols and things following the content of the file. I am not sure what is wrong, any help would be appreciated. Thank you.
char content[fd];
What?close()
.