Reputation: 339
The following is a program that copies the contents of a file (1st argument) to a new file (2nd argument).
I'm testing it on linux, so for instance, copying the contents of user's terminal onto new file also works:
./copy /dev/tty newFile
However, copying the contents of current directory does not work:
./copy . newFile
The latter does not cause an error when opening the 1st argument, but nothing is copied. I thought that the contents of the directory would be copied onto the new file?
EDIT : This happens because linux takes working directory by standard to be ~
copy.c program below:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int copy(int inFileDesc,int outFileDesc);
int main (int argc, char** argv)
{
int inputfd;
int outputfd;
if (argc!=3)
{
printf("Wrong number of arguments\n");
exit(1);
}
inputfd=open(argv[1],O_RDONLY);
if(inputfd==-1)
{
printf("Cannot open file\n");
exit(1);
}
outputfd=creat(argv[2],0666);
if(outputfd==-1)
{
printf("Cannot create file\n");
exit(1);
}
copy(inputfd,outputfd);
exit(0);
}
int copy(int inFileDesc,int outFileDesc)
{
int count;
char buffer[BUFSIZ];
while((count=read(inFileDesc,buffer,sizeof(buffer)))>0)
{
write(outFileDesc,buffer,count);
}
}
Upvotes: 1
Views: 71
Reputation: 392
If you read man 2 open
an man 2 read
man 2 open
The named file is opened unless:
...
[EISDIR] The named file is a directory, and the arguments specify that it is to
be opened for writing.
man 2 read
The pread(), read(), and readv() calls will succeed unless:
...
[EISDIR] An attempt is made to read a directory.
Therefore, open
will not fail because you specified O_RDONLY
and return your file descriptor, however read
will fail at first call.
Upvotes: 2