This program reads a filename from standard input and then prints its content. Please review:
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
int main()
{
char fileName[20];
// Get the filename from the user:
int fileNameLength = read(0,fileName,19);
// We need to get rid of the new line character caused by terminal
// Replace the new line character with \0
fileName[fileNameLength-1] = fileName[fileNameLength];
printf("You want to see the contents of: %s\n", fileName);
// open the file:
int fd = 0;
fd = open(fileName,O_RDONLY);
if(fd == -1) {
// Something went wrong, perhaps no such file:
perror(NULL);
printf("%s\n", fileName);
} else {
// Read until the read method returns 0 bytes.
char buf[20];
int numBytesRead = read(fd,buf,20);
while(numBytesRead) {
write(1,buf,numBytesRead);
numBytesRead = read(fd,buf,20);
}
close(fd);
}
puts("");
}
And in action:
Korays-MacBook-Pro:~ koraytugay$ gcc koray.c Korays-MacBook-Pro:~ koraytugay$ ./a.out k.txt You want to see the contents of: k.txt Hello Code Review! This is the contents of k.txt. Have a good day! Korays-MacBook-Pro:~ koraytugay$