Linux Basic Programming -3

Linux Basic Programming -3

·

2 min read

Systems Calls for I/O Operations:-

  1. Creat:-
    int creat(char *filename, mode_t mode);
    First parameter is filename and second is mode. Some most common modes are

O_RDONLY:- the file has read-only permission.

O_WRONLY:- This mode gives write permissions.

O_RDWR:- This mode gives both read and write permissions.

O_EXCL:- This flag mode prevents the creation of a file if it already exists.

O_APPEND:- This mode appends the content to existing file data without overriding it.

O_CREAT:- This flag mode creates a file if it does not exist.

If you want to use multiple modes at the same time, you can use the bitwise OR operator.

Program example:- devnationfile_1.c

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

int main()
{
int file_descriptor;
char filename[255];
printf("Enter the filename:");
scanf("%s", filename);
//setting permission to read and write access for the file
file_descriptor = creat(filename, O_RDWR | O_CREAT);

if(file_descriptor!=-1){
 printf("file created successfully", filename);
 }
else{
 printf("unable to create the file");
 }
  return 0;
}

Output:-

devnationfile_1.png

2.Open:-
int open(const char *filepath, int flags, ...);

#include<stdio.h>
#include<fcntl.h>
int main()
{
int file_descriptor;
char filename[255];
printf("Enter the filename:");
scanf("%s", filename);
 file_descriptor = open(filename, O_RDONLY);
if(file_descriptor!=-1){
 printf("%s file open successfully", filename);
 }
else{
 printf("unable to open the file%s ", filename);
 }  
  return 0;
}

3.Close:-
int close(int file_descriptor);

int close_status = close(file_descriptor);
   // Checks the condition and prints the appropriate statement.
   /*
    Success: 0
    Error: -1
    */
   if(close_status == 0){
       printf("File Descriptor is closed Successfully\n");
   }else{
       printf("File Descriptor is not closed\n");
   }

devnationfile_opem_close.png

A file descriptor is an integer value that identifies the open file in a process.These are the most common operations that you can perform on files. All program uses core system calls to manipulate the tasks. To get more information on a system call, you can use the man command. For example, man creat gives complete information on the creat system call. These system calls set an error number if they fail to perform the operation.

man_creat.png