File Handling With Open() Close() Read() Write() C Programming
Important Terminology
What is the File Descriptor?
File descriptor is integer that uniquely identifies an open file of the procedure.
File Descriptor tabular array: File descriptor tabular array is the collection of integer array indices that are file descriptors in which elements are pointers to file table entries. One unique file descriptors table is provided in operating organisation for each process.
File Tabular array Entry: File table entries is a structure In-memory surrogate for an open up file, which is created when process asking to opens file and these entries maintains file position.
Standard File Descriptors: When whatever process starts, then that process file descriptors table'south fd(file descriptor) 0, 1, ii open automatically, (By default) each of these iii fd references file table entry for a file named /dev/tty
/dev/tty: In-memory surrogate for the terminal
Terminal: Combination keyboard/video screen
Read from stdin => read from fd 0 : Whenever we write whatever grapheme from keyboard, it read from stdin through fd 0 and relieve to file named /dev/tty.
Write to stdout => write to fd 1 : Whenever we run across any output to the video screen, it's from the file named /dev/tty and written to stdout in screen through fd i.
Write to stderr => write to fd 2 : We see any error to the video screen, it is also from that file write to stderr in screen through fd two.
I/O System calls
Basically at that place are full 5 types of I/O organization calls:
1. Create: Used to Create a new empty file.
Syntax in C language: int create(char *filename, mode_t mode)
Parameter:
- filename : name of the file which yous want to create
- mode : indicates permissions of new file.
Returns:
- render offset unused file descriptor (generally three when first create use in procedure because 0, one, ii fd are reserved)
- return -one when error
How it work in Os
- Create new empty file on disk
- Create file table entry
- Set outset unused file descriptor to point to file table entry
- Render file descriptor used, -1 upon failure
two. open: Used to Open up the file for reading, writing or both.
Syntax in C language #include<sys/types.h> #include<sys/stat.h> #include <fcntl.h> int open (const char* Path, int flags [, int mode ]);
Parameters
- Path: path to file which you want to use
- use absolute path begin with "/", when you are non work in same directory of file.
- Use relative path which is only file name with extension, when y'all are work in aforementioned directory of file.
- flags : How you like to apply
- O_RDONLY: read only, O_WRONLY: write only, O_RDWR: read and write, O_CREAT: create file if it doesn't exist, O_EXCL: preclude cosmos if it already exists
How it works in OS
- Find the existing file on deejay
- Create file table entry
- Set starting time unused file descriptor to bespeak to file table entry
- Return file descriptor used, -ane upon failure
C
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
extern
int
errno
;
int
main()
{
int
fd = open up(
"foo.txt"
, O_RDONLY | O_CREAT);
printf
(
"fd = %d/north"
, fd);
if
(fd ==-ane)
{
printf
(
"Error Number % d\due north"
,
errno
);
perror
(
"Program"
);
}
return
0;
}
Output:
fd = 3
3. close: Tells the operating system you are done with a file descriptor and Close the file which pointed by fd.
Syntax in C language #include <fcntl.h> int close(int fd);
Parameter:
- fd :file descriptor
Return:
- 0 on success.
- -1 on error.
How it works in the OS
- Destroy file table entry referenced by element fd of file descriptor table
– As long as no other process is pointing to information technology! - Set chemical element fd of file descriptor tabular array to NULL
C
#include<stdio.h>
#include <fcntl.h>
int
main()
{
int
fd1 = open(
"foo.txt"
, O_RDONLY);
if
(fd1 < 0)
{
perror
(
"c1"
);
exit
(1);
}
printf
(
"opened the fd = % d\n"
, fd1);
if
(close(fd1) < 0)
{
perror
(
"c1"
);
exit
(1);
}
printf
(
"closed the fd.\northward"
);
}
Output:
opened the fd = 3 closed the fd.
C
#include<stdio.h>
#include<fcntl.h>
int
main()
{
int
fd1 = open(
"foo.txt"
, O_RDONLY, 0);
close(fd1);
int
fd2 = open(
"baz.txt"
, O_RDONLY, 0);
printf
(
"fd2 = % d\northward"
, fd2);
exit
(0);
}
Output:
fd2 = three
Hither, In this code first open() returns 3 considering when primary process created, so fd 0, 1, 2 are already taken by stdin, stdout and stderr. And then first unused file descriptor is 3 in file descriptor table. After that in shut() system call is free information technology this 3 file descriptor and then later set 3 file descriptor as zippo. And then when we called second open up(), and so first unused fd is besides 3. So, output of this program is 3.
4. read: From the file indicated by the file descriptor fd, the read() function reads cnt bytes of input into the memory surface area indicated by buf. A successful read() updates the access time for the file.
Syntax in C language size_t read (int fd, void* buf, size_t cnt);
Parameters:
- fd: file descriptor
- buf: buffer to read data from
- cnt: length of buffer
Returns: How many bytes were actually read
- return Number of bytes read on success
- return 0 on reaching end of file
- render -1 on fault
- return -i on signal interrupt
Of import points
- buf needs to point to a valid retention location with length non smaller than the specified size considering of overflow.
- fd should exist a valid file descriptor returned from open up() to perform read operation because if fd is NULL then read should generate error.
- cnt is the requested number of bytes read, while the return value is the actual number of bytes read. Likewise, some times read system call should read less bytes than cnt.
C
#include<stdio.h>
#include <fcntl.h>
int
chief()
{
int
fd, sz;
char
*c = (
char
*)
calloc
(100,
sizeof
(
char
));
fd = open(
"foo.txt"
, O_RDONLY);
if
(fd < 0) {
perror
(
"r1"
);
exit
(1); }
sz = read(fd, c, 10);
printf
(
"called read(% d, c, 10). returned that"
" %d bytes were read.\n"
, fd, sz);
c[sz] =
'\0'
;
printf
(
"Those bytes are as follows: % due south\n"
, c);
}
Output:
called read(3, c, ten). returned that ten bytes were read. Those bytes are equally follows: 0 0 0 foo.
Suppose that foobar.txt consists of the half-dozen ASCII characters "foobar". Then what is the output of the following plan?
C
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
int
primary()
{
char
c;
int
fd1 = open up(
"sample.txt"
, O_RDONLY, 0);
int
fd2 = open(
"sample.txt"
, O_RDONLY, 0);
read(fd1, &c, 1);
read(fd2, &c, one);
printf
(
"c = %c\north"
, c);
get out
(0);
}
Output:
c = f
The descriptors fd1 and fd2 each have their own open file table entry, and so each descriptor has its ain file position for foobar.txt . Thus, the read from fd2 reads the starting time byte of foobar.txt , and the output is c = f, non c = o.
5. write: Writes cnt bytes from buf to the file or socket associated with fd. cnt should non exist greater than INT_MAX (divers in the limits.h header file). If cnt is naught, write() simply returns 0 without attempting whatsoever other action.
#include <fcntl.h> size_t write (int fd, void* buf, size_t cnt);
Parameters:
- fd: file descriptor
- buf: buffer to write information to
- cnt: length of buffer
Returns: How many bytes were actually written
- render Number of bytes written on success
- return 0 on reaching end of file
- render -1 on error
- return -1 on signal interrupt
Important points
- The file needs to be opened for write operations
- buf needs to be at to the lowest degree equally long as specified by cnt considering if buf size less than the cnt then buf will atomic number 82 to the overflow condition.
- cnt is the requested number of bytes to write, while the return value is the actual number of bytes written. This happens when fd have a less number of bytes to write than cnt.
- If write() is interrupted past a signal, the effect is one of the following:
-If write() has not written whatsoever data yet, it returns -1 and sets errno to EINTR.
-If write() has successfully written some data, it returns the number of bytes it wrote before information technology was interrupted.
C
#include<stdio.h>
#include <fcntl.h>
chief()
{
int
sz;
int
fd = open(
"foo.txt"
, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if
(fd < 0)
{
perror
(
"r1"
);
exit
(1);
}
sz = write(fd,
"hello geeks\north"
,
strlen
(
"how-do-you-do geeks\n"
));
printf
(
"chosen write(% d, \"howdy geeks\\n\", %d)."
" It returned %d\n"
, fd,
strlen
(
"hi geeks\northward"
), sz);
close(fd);
}
Output:
called write(3, "how-do-you-do geeks\n", 12). it returned 11
Here, when you see in the file foo.txt after running the code, yous get a "hullo geeks". If foo.txt file already have some content in it then write arrangement call overwrite the content and all previous content are deleted and but "howdy geeks" content volition have in the file.
Impress "hello world" from the program without utilize whatsoever printf or cout office.
C
#include<stdio.h>
#include<cord.h>
#include<unistd.h>
#include<fcntl.h>
int
main (
void
)
{
int
fd[2];
char
buf1[12] =
"hi world"
;
char
buf2[12];
fd[0] = open up(
"foobar.txt"
, O_RDWR);
fd[1] = open(
"foobar.txt"
, O_RDWR);
write(fd[0], buf1,
strlen
(buf1));
write(ane, buf2, read(fd[1], buf2, 12));
close(fd[0]);
close(fd[1]);
render
0;
}
Output:
howdy earth
In this code, buf1 array's cord "hello world" is get-go write in to stdin fd[0] then after that this string write into stdin to buf2 array. Afterwards that write into buf2 assortment to the stdout and print output " how-do-you-do world ".
This article is contributed by Kadam Patel. If you like GeeksforGeeks and would like to contribute, you tin as well write an article using write.geeksforgeeks.org or mail your article to review-squad@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you desire to share more information most the topic discussed above.
Source: https://www.geeksforgeeks.org/input-output-system-calls-c-create-open-close-read-write/
0 Response to "File Handling With Open() Close() Read() Write() C Programming"
Post a Comment