SlideShare una empresa de Scribd logo
1 de 55
FILE IO
UNIX SYSTEM
PROGRAMMING
Components of file system
Boot block:
Contains boot strap code.
Super block:
Stores File system information.
Inode list:
Stores basic information about files.
Data block:
Stores the actual data of file.
Boot Block Super Block Inode Blocks Data Blocks
Super Block
The Super block describes the state of the file system.
Super Block consists of:
 Size of the file system
 No. of free blocks in the file system
 List of free blocks available in the file system
 Index of the next free block in the free block list
 Size of the i-node list
No. of free i-nodes in the file system
 Index of the next free i-node in the file system
inode
Contains the information necessary for a process to access a
file.
Exists in static form on the disk.
Struct inode contains following info:
File ownership
File type and access permissions
Time stamp: Creation time, Modification time, last
access
Hard link count
File size
Address of data blocks associated with the file.
(Array of 13 pointers)
These inodes are also called as disk inodes
Inode structure
File Related System Calls
int open(const char *pathname , int flag); Macro Descripti
on
O_RDONLY One of
these is
mustO_WRONLY
O_RDWR
O_APPEND These are
optional.
O_TRUNC
O_CREAT
Open an non-existing file in readonly
mode and check the return value.
Open an existing file in readonly mode
and check the return value.
Open an existing file in writeonly mode and check the
return value.
Check if the existing data in file is deleted or not.
Open an non-existing file in writeonly
mode and check the return value.
File Related System Call
System Call Description Return Value
Open open and possibly create a file Failure = -1
Success = File
Descriptor
Read read from a file descriptor Error : -1
No Data : 0
Success : Number of
Bytes read
Write write to a file descriptor Error : -1
Success : Number of
Bytes written
close close a file descriptor Failure : -1
Success : 0
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
int fd = open(argv[1] , O_RDONLY);
if(fd == -1)
printf("Unable to open file n");
else
{
printf("File Opened Successfully n");
printf("File Descriptor = %d n" , fd);
}
}
C – fopen Linux – open System call
r O_RDONLY
w O_WRONLY | O_TRUNC | O_CREAT
a O_WRONLY | O_APPEND | O_CREAT
r+ O_RDWR
w+ O_RDWR | O_TRUNC | O_CREAT
a+ O_RDWR | O_APPEND | O_CREAT
Open
Open returns the first free available file descriptor
Every open call returns a new file descriptor.
File Related System Call : write
ssize_t write(int fd, void *buf, size_t count);
int fd = open(argv[1] , O_WRONLY);
char str[40] = "";
while(fgets(str , 39,stdin) != NULL)
{
write(fd , str , 39);
}
Return value :
0 – Nothing was written
-1 – Error
Success : >0 (number of bytes written)
Write a program to read data from stdin and write to file.
File Related System Calls
How to create a new file.
Macro
O_RDONLY
O_WRONLY
O_RDWR
O_APPEND
O_TRUNC
O_CREAT
open(“newfile.txt" , O_WRONLY | O_CREAT);
What happens if you open an existing file
with O_WRONLY | O_CREAT mode. The
contents will be retained or deleted
How to write data at end of file.
open(“append.txt" , O_WRONLY | O_APPEND);
How to clear the contents of file.
open(argv[1] , O_WRONLY | O_TRUNC);
File Related System Calls
int open(const char *pathname, int flags, mode_t mode);
Mode – File permissions
Specify the mode value in hex like 0666 etc, and verify if the
specified permissions are set for file
Mode & ~umask
File Related System Calls
int creat(const char *pathname, mode_t mode);
creat opens file for write only.
similar to
open (pathname, O_WRONLY | O_CREAT | O_TRUNC, mode);
Mode – File permissions
int close(int filedescriptor);
What will be the fd value (output).
void func()
{
int fd = open("test1.txt" , O_WRONLY);
printf(" %d " , fd);
}
int main()
{
func();
func();
}
Write a program to implement cp command
$cp sourcefile destinationfile
Open source file in readmode
Open destination file in write mode.
Read data from source file and write to dest file.
Write a program to implement cat command
$cat filename
Open source file in readmode
Set stdout as the destfile (fd = 1)
Read data from source file and write to dest file.
Implement cat command.
$cat
Read descriptor – 0
Write descriptor - 1
fdr = 0;
fdw = 1;
Implement cat command.
$cat outfile
Read descriptor – 0
Write descriptor – return value of open function.(>=
3)
Implement cat command:Input file to stdout.
$cat inpfile
Write descriptor– 1
Read descriptor – return value of open function.(>= 3)
lseek
off_t lseek(int fildes, off_t offset, int whence);
What happens if offset is greater than the size of file.
The lseek function allows the file offset to be set
beyond the end of the exist-ing end-of-file of the file
Can Multiple File Descriptors point to same File
Table? (Yes)
Every open adds a new entry in FDT and FT.
Demonstration using multiple open sys call and
checking the return values (eg: 3 and 4).
Dup System call is used to Create a copy (or duplicate)
int dup(int oldfd);
 dup uses the lowest-numbered unused descriptor for
the new descriptor.
int dup2(int oldfd,int new fd);
 dup2 makes newfd be the copy of oldfd, closing newfd
first if necessary.
Difference Between Dup and Open
Open
3
4
Dup
3
4
Program to make printf write to file - using dup
#include <stdio.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
int fd = open(argv[1] , O_WRONLY);
close(1);
dup(fd);
printf("This statement was written using printf n");
cout <<"This statement was written using cout " << endl;}
Program to make printf write to file - using dup2
#include <stdio.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
int fd = open(argv[1] , O_WRONLY);
int newfd = dup2(fd , 1);
printf("HELLO WORLD n");
}
FILE LOCKING
struct flock
{
short l_type; /* F_RDLCK, F_WRLCK, F_UNLCK */
short l_whence; /*SEEK_SET, SEEK_CUR, SEEK_END */
off_t l_start; /* Starting offset for lock */
off_t l_len; /* Number of bytes to lock */
pid_t l_pid; /* PID of process blocking our lock
(F_GETLK only) */
};
F_GETLK Get lock
F_SETLK Set lock
F_SETLKW Set lock wait if
the lock is free.
Simultaneous Write to same file
Setting a Lock - Exclusive Lock
Setting a Lock - Exclusive Lock
Shared Lock
Run these two programs simultaneously in two different terminals and
observe the output
P1 P2
READ READ SUCCESS
READ WRITE FAILURE
WRITE READ FAILURE
WRITE WRITE FAILURE
Wait for other lock to release
SETLKW
F_SETLKW
Run these two programs simultaneously in two different terminals and
observe the output
mkdir
int main()
{
char dirname[20];
printf("Enter the directory name : " );
scanf("%s",dirname);
if(mkdir(dirname , 0666) == 0)
printf("Directory %s created n " , dirname);
else
printf("Unable to create directory ");
return 0;
}
Hardlink and Softlink
Softlink is similar to shortcut in windows, if original
file is deleted, the shortcut is useless (dangling).
Hardlink is similar(not same) to copying a file.
Even if the original file is deleted, the hardlink file will
contain the data.
ln existingfile newfile
Hardlink
ln –s existingfile newfile
softlink
Record Locking
Hardlink
The size and inode number in hardlink remains the same.
ln myfile.txt hardlink.txt
File Name Myfile.txt
Contents CRANES VARSITY
Long listing 2955996 -rw-rw-r-- 1 sik sik 15 Aug 30 19:00 myfile.txt
File Name hardlink.t
xt
Contents CRANES
VARSITY
2955996 -rw-rw-r-- 2 sik sik 15 Aug 30 19:00 hardlink.txt
2955996 -rw-rw-r-- 2 sik sik 15 Aug 30 19:00 myfile.txt
Softlink
The size and inode number in softlink is different.
ln -s myfile.txt softlink.txt
File Name Myfile.txt Description
Contents CRANES VARSITY
Long listing -rw-rw-r-- 1 sik sik 15
File Name softlin
k.txt
2955996 -rw-rw-r-- 1 sik sik 15 Aug 30 19:00 myfile.txt
2955993 lrwxrwxrwx 1 sik sik 10 Aug 30 19:06 softlink.txt ->
myfile.txt
System calls for Links
Hardlink
int link(const char *oldfile , const char *newfile);
Softlink
int symlink(const char *oldfile , const char
*newfile);
Unlink - Remove a file
int unlink(const char *file);
Return Value:
0 – success
-1 – error
Hardlink
if oldfile is not present, link call fails(-1).
Softlink
if oldfile is not present, symlink call will be
successful(0).
link(filepresent , newfile);
Success
link(filenotpresent , newfile); Failure
symlink(filenotpresent , newfile);
success

Más contenido relacionado

La actualidad más candente (20)

File Management in C
File Management in CFile Management in C
File Management in C
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
File handling in C
File handling in CFile handling in C
File handling in C
 
file
filefile
file
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File operations in c
File operations in cFile operations in c
File operations in c
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling in c
File  handling in cFile  handling in c
File handling in c
 
File in C language
File in C languageFile in C language
File in C language
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
 
File handling-c
File handling-cFile handling-c
File handling-c
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File handling
File handlingFile handling
File handling
 
Python - File operations & Data parsing
Python - File operations & Data parsingPython - File operations & Data parsing
Python - File operations & Data parsing
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
 
Python-files
Python-filesPython-files
Python-files
 
File Management
File ManagementFile Management
File Management
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 

Similar a File management

Linux 系統程式--第一章 i/o 函式
Linux 系統程式--第一章 i/o 函式Linux 系統程式--第一章 i/o 函式
Linux 系統程式--第一章 i/o 函式艾鍗科技
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.pptyuvrajkeshri
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentalssirmanohar
 
18CS56-UP-Module 3.pptx
18CS56-UP-Module 3.pptx18CS56-UP-Module 3.pptx
18CS56-UP-Module 3.pptxChenamPawan
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfsudhakargeruganti
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10patcha535
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYRajeshkumar Reddy
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxAssadLeo1
 

Similar a File management (20)

Unix-module3.pptx
Unix-module3.pptxUnix-module3.pptx
Unix-module3.pptx
 
Linux 系統程式--第一章 i/o 函式
Linux 系統程式--第一章 i/o 函式Linux 系統程式--第一章 i/o 函式
Linux 系統程式--第一章 i/o 函式
 
Unit5
Unit5Unit5
Unit5
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Linux basics
Linux basicsLinux basics
Linux basics
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
 
18CS56-UP-Module 3.pptx
18CS56-UP-Module 3.pptx18CS56-UP-Module 3.pptx
18CS56-UP-Module 3.pptx
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
Systemcall1
Systemcall1Systemcall1
Systemcall1
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
working with files
working with filesworking with files
working with files
 
Unix
UnixUnix
Unix
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 

Más de Mohammed Sikander (20)

Operator Overloading in C++
Operator Overloading in C++Operator Overloading in C++
Operator Overloading in C++
 
Python_Regular Expression
Python_Regular ExpressionPython_Regular Expression
Python_Regular Expression
 
Modern_CPP-Range-Based For Loop.pptx
Modern_CPP-Range-Based For Loop.pptxModern_CPP-Range-Based For Loop.pptx
Modern_CPP-Range-Based For Loop.pptx
 
Modern_cpp_auto.pdf
Modern_cpp_auto.pdfModern_cpp_auto.pdf
Modern_cpp_auto.pdf
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Python strings
Python stringsPython strings
Python strings
 
Python set
Python setPython set
Python set
 
Python list
Python listPython list
Python list
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Pointer basics
Pointer basicsPointer basics
Pointer basics
 
Signal
SignalSignal
Signal
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Java strings
Java   stringsJava   strings
Java strings
 
Java notes 1 - operators control-flow
Java notes   1 - operators control-flowJava notes   1 - operators control-flow
Java notes 1 - operators control-flow
 

Último

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 

Último (20)

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 

File management

  • 2. Components of file system Boot block: Contains boot strap code. Super block: Stores File system information. Inode list: Stores basic information about files. Data block: Stores the actual data of file. Boot Block Super Block Inode Blocks Data Blocks
  • 3. Super Block The Super block describes the state of the file system. Super Block consists of:  Size of the file system  No. of free blocks in the file system  List of free blocks available in the file system  Index of the next free block in the free block list  Size of the i-node list No. of free i-nodes in the file system  Index of the next free i-node in the file system
  • 4. inode Contains the information necessary for a process to access a file. Exists in static form on the disk. Struct inode contains following info: File ownership File type and access permissions Time stamp: Creation time, Modification time, last access Hard link count File size Address of data blocks associated with the file. (Array of 13 pointers) These inodes are also called as disk inodes
  • 6. File Related System Calls int open(const char *pathname , int flag); Macro Descripti on O_RDONLY One of these is mustO_WRONLY O_RDWR O_APPEND These are optional. O_TRUNC O_CREAT Open an non-existing file in readonly mode and check the return value. Open an existing file in readonly mode and check the return value. Open an existing file in writeonly mode and check the return value. Check if the existing data in file is deleted or not. Open an non-existing file in writeonly mode and check the return value.
  • 7. File Related System Call System Call Description Return Value Open open and possibly create a file Failure = -1 Success = File Descriptor Read read from a file descriptor Error : -1 No Data : 0 Success : Number of Bytes read Write write to a file descriptor Error : -1 Success : Number of Bytes written close close a file descriptor Failure : -1 Success : 0
  • 8. #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main(int argc,char *argv[]) { int fd = open(argv[1] , O_RDONLY); if(fd == -1) printf("Unable to open file n"); else { printf("File Opened Successfully n"); printf("File Descriptor = %d n" , fd); } }
  • 9. C – fopen Linux – open System call r O_RDONLY w O_WRONLY | O_TRUNC | O_CREAT a O_WRONLY | O_APPEND | O_CREAT r+ O_RDWR w+ O_RDWR | O_TRUNC | O_CREAT a+ O_RDWR | O_APPEND | O_CREAT
  • 10. Open Open returns the first free available file descriptor
  • 11.
  • 12. Every open call returns a new file descriptor.
  • 13.
  • 14. File Related System Call : write ssize_t write(int fd, void *buf, size_t count); int fd = open(argv[1] , O_WRONLY); char str[40] = ""; while(fgets(str , 39,stdin) != NULL) { write(fd , str , 39); } Return value : 0 – Nothing was written -1 – Error Success : >0 (number of bytes written) Write a program to read data from stdin and write to file.
  • 15.
  • 16. File Related System Calls How to create a new file. Macro O_RDONLY O_WRONLY O_RDWR O_APPEND O_TRUNC O_CREAT open(“newfile.txt" , O_WRONLY | O_CREAT); What happens if you open an existing file with O_WRONLY | O_CREAT mode. The contents will be retained or deleted How to write data at end of file. open(“append.txt" , O_WRONLY | O_APPEND); How to clear the contents of file. open(argv[1] , O_WRONLY | O_TRUNC);
  • 17. File Related System Calls int open(const char *pathname, int flags, mode_t mode); Mode – File permissions Specify the mode value in hex like 0666 etc, and verify if the specified permissions are set for file Mode & ~umask
  • 18. File Related System Calls int creat(const char *pathname, mode_t mode); creat opens file for write only. similar to open (pathname, O_WRONLY | O_CREAT | O_TRUNC, mode); Mode – File permissions int close(int filedescriptor);
  • 19. What will be the fd value (output). void func() { int fd = open("test1.txt" , O_WRONLY); printf(" %d " , fd); } int main() { func(); func(); }
  • 20. Write a program to implement cp command $cp sourcefile destinationfile Open source file in readmode Open destination file in write mode. Read data from source file and write to dest file.
  • 21.
  • 22. Write a program to implement cat command $cat filename Open source file in readmode Set stdout as the destfile (fd = 1) Read data from source file and write to dest file.
  • 23. Implement cat command. $cat Read descriptor – 0 Write descriptor - 1 fdr = 0; fdw = 1;
  • 24. Implement cat command. $cat outfile Read descriptor – 0 Write descriptor – return value of open function.(>= 3)
  • 25. Implement cat command:Input file to stdout. $cat inpfile Write descriptor– 1 Read descriptor – return value of open function.(>= 3)
  • 26. lseek off_t lseek(int fildes, off_t offset, int whence); What happens if offset is greater than the size of file. The lseek function allows the file offset to be set beyond the end of the exist-ing end-of-file of the file
  • 27.
  • 28. Can Multiple File Descriptors point to same File Table? (Yes) Every open adds a new entry in FDT and FT. Demonstration using multiple open sys call and checking the return values (eg: 3 and 4). Dup System call is used to Create a copy (or duplicate)
  • 29. int dup(int oldfd);  dup uses the lowest-numbered unused descriptor for the new descriptor. int dup2(int oldfd,int new fd);  dup2 makes newfd be the copy of oldfd, closing newfd first if necessary.
  • 33.
  • 34. Program to make printf write to file - using dup #include <stdio.h> #include <fcntl.h> int main(int argc,char *argv[]) { int fd = open(argv[1] , O_WRONLY); close(1); dup(fd); printf("This statement was written using printf n"); cout <<"This statement was written using cout " << endl;}
  • 35. Program to make printf write to file - using dup2 #include <stdio.h> #include <fcntl.h> int main(int argc,char *argv[]) { int fd = open(argv[1] , O_WRONLY); int newfd = dup2(fd , 1); printf("HELLO WORLD n"); }
  • 36.
  • 37. FILE LOCKING struct flock { short l_type; /* F_RDLCK, F_WRLCK, F_UNLCK */ short l_whence; /*SEEK_SET, SEEK_CUR, SEEK_END */ off_t l_start; /* Starting offset for lock */ off_t l_len; /* Number of bytes to lock */ pid_t l_pid; /* PID of process blocking our lock (F_GETLK only) */ };
  • 38. F_GETLK Get lock F_SETLK Set lock F_SETLKW Set lock wait if the lock is free.
  • 40. Setting a Lock - Exclusive Lock
  • 41. Setting a Lock - Exclusive Lock
  • 42. Shared Lock Run these two programs simultaneously in two different terminals and observe the output
  • 43. P1 P2 READ READ SUCCESS READ WRITE FAILURE WRITE READ FAILURE WRITE WRITE FAILURE
  • 44. Wait for other lock to release SETLKW
  • 45.
  • 46. F_SETLKW Run these two programs simultaneously in two different terminals and observe the output
  • 47. mkdir int main() { char dirname[20]; printf("Enter the directory name : " ); scanf("%s",dirname); if(mkdir(dirname , 0666) == 0) printf("Directory %s created n " , dirname); else printf("Unable to create directory "); return 0; }
  • 48. Hardlink and Softlink Softlink is similar to shortcut in windows, if original file is deleted, the shortcut is useless (dangling). Hardlink is similar(not same) to copying a file. Even if the original file is deleted, the hardlink file will contain the data. ln existingfile newfile Hardlink ln –s existingfile newfile softlink
  • 50.
  • 51.
  • 52. Hardlink The size and inode number in hardlink remains the same. ln myfile.txt hardlink.txt File Name Myfile.txt Contents CRANES VARSITY Long listing 2955996 -rw-rw-r-- 1 sik sik 15 Aug 30 19:00 myfile.txt File Name hardlink.t xt Contents CRANES VARSITY 2955996 -rw-rw-r-- 2 sik sik 15 Aug 30 19:00 hardlink.txt 2955996 -rw-rw-r-- 2 sik sik 15 Aug 30 19:00 myfile.txt
  • 53. Softlink The size and inode number in softlink is different. ln -s myfile.txt softlink.txt File Name Myfile.txt Description Contents CRANES VARSITY Long listing -rw-rw-r-- 1 sik sik 15 File Name softlin k.txt 2955996 -rw-rw-r-- 1 sik sik 15 Aug 30 19:00 myfile.txt 2955993 lrwxrwxrwx 1 sik sik 10 Aug 30 19:06 softlink.txt -> myfile.txt
  • 54. System calls for Links Hardlink int link(const char *oldfile , const char *newfile); Softlink int symlink(const char *oldfile , const char *newfile); Unlink - Remove a file int unlink(const char *file); Return Value: 0 – success -1 – error
  • 55. Hardlink if oldfile is not present, link call fails(-1). Softlink if oldfile is not present, symlink call will be successful(0). link(filepresent , newfile); Success link(filenotpresent , newfile); Failure symlink(filenotpresent , newfile); success

Notas del editor

  1. 3
  2. 4
  3. 6
  4. Try opening a non-existing file. Try to open an existing file which has read permission. Try to open an existing file which does not have read permission. ----------------------------------------------------------------------------------- #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main(int argc,char *argv[]) { int fd = open(argv[1] , O_RDONLY); if(fd == -1) printf("Unable to open file \n"); else { printf("File Opened Successfully \n"); printf("File Descriptor = %d \n" , fd); } }
  5. #include <stdio.h> #include <fcntl.h> int main() { int fd1 = open("a.txt" , O_RDONLY); int fd2 = open("b.txt" , O_RDONLY); int fd3 = open("c.txt" , O_RDONLY); printf("fd1 = %d \n" ,fd1); printf("fd2 = %d \n" ,fd2); printf("fd3 = %d \n" ,fd3); close(fd2); int fd4 = open("d.txt" , O_RDONLY); printf("fd4 = %d \n" ,fd4); return 0; }
  6. #include <fcntl.h> #include <stdio.h> int main() { int fd = open("fruits.txt" , O_RDONLY); char buffer[20] = ""; int len; while((len = read(fd , buffer , 19)) > 0) { buffer[len] = '\0'; printf(buffer); } printf("Len = %d \n" , len); }
  7. 14
  8. 16
  9. 17
  10. 18
  11. 19
  12. 20
  13. 22
  14. 23
  15. 24
  16. 25
  17. 26
  18. #include <stdio.h> #include <stdlib.h> #include <fcntl.h> int main(int argc,char *argv[]) { if(argc < 2) { printf("Missing argument : ./a.out file \n"); exit(EXIT_FAILURE); } int fdr = open(argv[1] , O_RDONLY); if(fdr == -1) { printf("Unable to open file \n"); exit(EXIT_FAILURE); } char str[21] = ""; int len; while( (len = read(fdr , str , 20)) != 0) { str[len] = '\0'; write(1 , str , len); printf(" - Position = %d \n" , lseek(fdr , 0 , SEEK_CUR)); } printf("\n Repeating the contents of file \n"); lseek(fdr , 0 , SEEK_SET); while( (len = read(fdr , str , 20)) != 0) { str[len] = '\0'; write(1 , str , len); } close(fdr); }
  19. 29
  20. #include <stdio.h> #include <fcntl.h> int main(int argc,char *argv[]) { int fd = open(argv[1] , O_WRONLY); int newfd = dup2(fd , 1); printf("HELLO WORLD \n"); }
  21. #include <stdio.h> #include <fcntl.h> int compare(const void *a,const void *b) { return *(const int *)a - *(const int *)b; } int main(int argc, char *argv[]) { int fdr = open(argv[1] , O_RDONLY); int fdw = open(argv[2] , O_WRONLY | O_TRUNC | O_CREAT , 0600); dup2(fdr , 0); dup2(fdw , 1); int n; scanf(" %d",&n); int arr[n] , i; for(i = 0 ; i < n ; i++) scanf(" %d", &arr[i]); qsort(arr , n , sizeof(int) , compare); for(i = 0 ; i < n ; i++) printf("%d\n", arr[i]); }
  22. Run these two programs simultaneously in two different terminals and observe the output Expected Output : AAABABABABABABABABBB
  23. 40
  24. #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> //Program - p2.c int main(int argc,char *argv[]) { int fd = open(argv[1] , O_WRONLY | O_APPEND | O_CREAT , 0666); struct flock lock = {.l_type = F_WRLCK , .l_whence = SEEK_SET, .l_start = 0, .l_len = 0 , .l_pid = getpid() }; if( fcntl(fd , F_SETLKW , &lock) == -1) { printf("Unable to set lock on p2 \n"); exit(0); } printf("Acquired lock in p2 \n"); for(int i = 0 ; i < 10 ; i++) { write(fd , "B" , 1); sleep(1); } }
  25. 42
  26. 46
  27. #include <unistd.h> #include <fcntl.h> #include <sys/types.h> int main(int argc,char *argv[]) { int fd = open(argv[1] , O_RDWR | O_CREAT , 0666); struct flock lock; lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; //Locking the first 10 Bytes of file lock.l_len = 10; lock.l_pid = getpid(); if(fcntl(fd , F_SETLKW , &lock) == -1) { printf("Unable to set lock \n"); return 1; } printf("p1 - Acquired Lock \n"); printf("Press Enter to release the lock \n"); getchar(); close(fd); printf("P1 COMPLETED \n"); return 0; }
  28. 55