Code Skips Over Output File Name and Reads Txt File Correctly C++
Important Terminology
What is the File Descriptor?
File descriptor is integer that uniquely identifies an open file of the process.
File Descriptor tabular array: File descriptor table is the collection of integer array indices that are file descriptors in which elements are pointers to file tabular array entries. One unique file descriptors tabular array is provided in operating system for each process.
File Tabular array Entry: File table entries is a construction In-memory surrogate for an open file, which is created when process asking to opens file and these entries maintains file position.
Standard File Descriptors: When any process starts, then that procedure file descriptors table's fd(file descriptor) 0, ane, 2 open automatically, (By default) each of these three fd references file tabular array entry for a file named /dev/tty
/dev/tty: In-memory surrogate for the terminal
Concluding: Combination keyboard/video screen
Read from stdin => read from fd 0 : Whenever we write any character from keyboard, it read from stdin through fd 0 and salvage to file named /dev/tty.
Write to stdout => write to fd 1 : Whenever we see any output to the video screen, it's from the file named /dev/tty and written to stdout in screen through fd 1.
Write to stderr => write to fd ii : We see whatever mistake to the video screen, information technology is likewise from that file write to stderr in screen through fd 2.
I/O System calls
Basically there are total five types of I/O system calls:
one. Create: Used to Create a new empty file.
Syntax in C language: int create(char *filename, mode_t way)
Parameter:
- filename : name of the file which yous want to create
- manner : indicates permissions of new file.
Returns:
- return outset unused file descriptor (generally three when starting time create use in procedure because 0, i, 2 fd are reserved)
- return -1 when error
How information technology work in Os
- Create new empty file on disk
- Create file table entry
- Set get-go unused file descriptor to point to file table entry
- Return file descriptor used, -i upon failure
2. open: Used to Open 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 way ]);
Parameters
- Path: path to file which you want to employ
- apply absolute path begin with "/", when you are not work in same directory of file.
- Use relative path which is only file name with extension, when you are work in same directory of file.
- flags : How you similar to utilize
- O_RDONLY: read simply, O_WRONLY: write only, O_RDWR: read and write, O_CREAT: create file if information technology doesn't exist, O_EXCL: forestall creation if it already exists
How it works in OS
- Find the existing file on deejay
- Create file table entry
- Set start unused file descriptor to signal to file table entry
- Render file descriptor used, -one upon failure
C
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
extern int errno ;
int master()
{
int fd = open( "foo.txt" , O_RDONLY | O_CREAT);
printf ( "fd = %d/n" , fd);
if (fd ==-1)
{
printf ( "Fault Number % d\n" , errno );
perror ( "Program" );
}
return 0;
}
Output:
fd = 3
three. close: Tells the operating system you are done with a file descriptor and Shut the file which pointed by fd.
Syntax in C linguistic communication #include <fcntl.h> int close(int fd);
Parameter:
- fd :file descriptor
Return:
- 0 on success.
- -one on fault.
How it works in the Bone
- Destroy file table entry referenced past element fd of file descriptor table
– Every bit long as no other process is pointing to it! - Set element fd of file descriptor tabular array to Naught
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 (shut(fd1) < 0)
{
perror ( "c1" );
go out (1);
}
printf ( "closed the fd.\n" );
}
Output:
opened the fd = iii 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 = 3
Here, In this code showtime open() returns 3 considering when master process created, then fd 0, 1, 2 are already taken past stdin, stdout and stderr. And then starting time unused file descriptor is iii in file descriptor table. Afterward that in close() system telephone call is free it this three file descriptor and then later on set 3 file descriptor as null. And then when nosotros called second open(), so first unused fd is also 3. So, output of this program is iii.
4. read: From the file indicated past the file descriptor fd, the read() function reads cnt bytes of input into the memory area indicated by buf. A successful read() updates the admission 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 information from
- cnt: length of buffer
Returns: How many bytes were actually read
- render Number of bytes read on success
- return 0 on reaching end of file
- render -1 on error
- render -ane on signal interrupt
Important points
- buf needs to point to a valid memory location with length not smaller than the specified size considering of overflow.
- fd should exist a valid file descriptor returned from open() to perform read performance considering if fd is Nada and then read should generate error.
- cnt is the requested number of bytes read, while the render value is the actual number of bytes read. Also, 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, x);
printf ( "called read(% d, c, 10). returned that"
" %d bytes were read.\northward" , fd, sz);
c[sz] = '\0' ;
printf ( "Those bytes are as follows: % due south\n" , c);
}
Output:
called read(3, c, ten). returned that 10 bytes were read. Those bytes are as follows: 0 0 0 foo.
Suppose that foobar.txt consists of the vi 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( "sample.txt" , O_RDONLY, 0);
int fd2 = open( "sample.txt" , O_RDONLY, 0);
read(fd1, &c, ane);
read(fd2, &c, 1);
printf ( "c = %c\due north" , c);
exit (0);
}
Output:
c = f
The descriptors fd1 and fd2 each take their own open file table entry, so each descriptor has its own file position for foobar.txt . Thus, the read from fd2 reads the beginning byte of foobar.txt , and the output is c = f, not c = o.
five. write: Writes cnt bytes from buf to the file or socket associated with fd. cnt should not exist greater than INT_MAX (defined in the limits.h header file). If cnt is zero, write() just returns 0 without attempting whatever other activity.
#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
- render 0 on reaching end of file
- return -1 on error
- return -ane on bespeak interrupt
Important points
- The file needs to be opened for write operations
- buf needs to be at to the lowest degree as long equally specified by cnt because if buf size less than the cnt and then buf volition pb 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 accept a less number of bytes to write than cnt.
- If write() is interrupted by a signal, the upshot is 1 of the following:
-If write() has not written any information however, it returns -1 and sets errno to EINTR.
-If write() has successfully written some data, it returns the number of bytes it wrote earlier it was interrupted.
C
#include<stdio.h>
#include <fcntl.h>
main()
{
int sz;
int fd = open up( "foo.txt" , O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0)
{
perror ( "r1" );
leave (1);
}
sz = write(fd, "how-do-you-do geeks\due north" , strlen ( "hello geeks\n" ));
printf ( "called write(% d, \"hi geeks\\n\", %d)."
" It returned %d\northward" , fd, strlen ( "how-do-you-do geeks\due north" ), sz);
close(fd);
}
Output:
called write(3, "hello geeks\due north", 12). it returned xi
Here, when you run into in the file foo.txt afterwards running the code, you get a "hello geeks". If foo.txt file already accept some content in it then write organization call overwrite the content and all previous content are deleted and only "hello geeks" content will have in the file.
Impress "hello world" from the programme without utilise any printf or cout function.
C
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
int main ( void )
{
int fd[2];
char buf1[12] = "hello globe" ;
char buf2[12];
fd[0] = open( "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:
hello world
In this code, buf1 array's string "how-do-you-do world" is first write in to stdin fd[0] and so later that this string write into stdin to buf2 assortment. After that write into buf2 array to the stdout and print output " hello world ".
This commodity is contributed past Kadam Patel. If you similar GeeksforGeeks and would like to contribute, you can as well write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks chief page and assist other Geeks.
Please write comments if you lot notice anything incorrect, or yous desire to share more information about the topic discussed above.
Source: https://www.geeksforgeeks.org/input-output-system-calls-c-create-open-close-read-write/
0 Response to "Code Skips Over Output File Name and Reads Txt File Correctly C++"
Post a Comment