Pegasus Pegasus - 2 months ago 17
C Question

System calls in C (File Descriptor)

follwing code has written to open a file and write data to terminal using sysyem calls in linux.

To read the value of the file descriptor (fd) it should assign a value. As we know in if else statement, from if part else part or else if part one part will implement at a time. So according to following code fd will have a value only at else if line. But when I pass a file name and run this program it opens the file. File opening is happen in while loop from read(() system call. But while loop is in else part and since file descriptor can't have any value theoretically. So how does the read function get recognize the file exactly? This is confusing me.

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

#define SIZE 10

int main(int argc, char *argv[])
{
int fd,n;
char buff[SIZE];

if(argc != 2)
{
printf("USAGE : %s\n",argv[0] );
exit(1);
}
else if ((fd = open(argv[1],0)) == -1)
{
perror("STATUS");
exit(1);
}
else
{
while((n = read(fd,buff,SIZE)) > 0)
{
write(1,buff,SIZE);

}
close(fd);
}
}

Answer

Following happens here:

Let's suppose the program is started with xyz.txt on the command line and let's suppose the xyz.txt file does exist:

if(argc != 2)
{
                                        // we don't get here because argc == 2
    printf("USAGE : %s\n",argv[0] );
    exit(1);
}
else if ((fd = open(argv[1],0)) == -1)  // the statement in the if clause will therefore
                                        // be executed, fd will be something different 
                                        // from -1 because open succeeded
{
    perror("STATUS");                   // therefore we dont ge here either
    exit(1);
}
else
{                                       // instead we get here and
    while((n = read(fd,buff,SIZE)) > 0) // everything works as expected
    {
        write(1,buff,SIZE);

    }
    close(fd);
}
Comments