How to open file through c program using POSIX API ?

Today we will learn basic open() command of the linux .Look at the following program

First explore basics of read() and open() through following link.

open()

read()

Create one hello.txt file using vi editor.

sudo vi /hello.txt

write “hello” inside the file .

I believe beginner didn’t get what file descriptor is (Did U !! You probably intelligent then 🙂 )

Those who don’t.  File descriptor is non negative number.Every file whenever we open the file one entry will be created inside the kernel for that file. If the file Descriptor value is negative than OS will throw an error.Maximum value of file descriptor can be OPEN_MAX.

REMEMBER: whenever we open or create any file , the kernel returns a file descriptor to process.

REMEMBER: UNIX System shells associates the file descriptor 0 with Standard Input of a process, file descriptor 1 with Standard Output, and file descriptor 2 with Standard Error.

Compile and  execute following open.c program.

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#define BLOCK_SIZE 4096
int main()
{
int fd=-1;
char buff[50];
int i=0;
ssize_t bytes_read=-1;
fd=open(“/hello.txt”,O_RDONLY);
if(-1==fd)
{
perror(“Open failed”);
return 1;
}
while((bytes_read=read(fd,buff,BLOCK_SIZE))>0)
{
printf(“bytes_read=%d\n”,bytes_read);

}
while(buff[i]!=”)
{
printf(“buff[%d]=%c\n”,i,buff[i]);
i++;
}
close(fd);
return 0;
}

Sample Output

bytes_read=6

buff[0]=H

buff[1]=e

buff[2]=l

buff[3]=l

buff[4]=o

buff[5]=

 

I hope you understand the simple open.c program .Best exercise to do with this program is try to dynamically allocate memory to the buffer .If you have any doubt I am here just a comment far away from you