Write a C Program That Reads the First 10 Lines of a File and Outputs With Stdout

Important Terminology

What is the File Descriptor?
File descriptor is integer that uniquely identifies an open file of the procedure.

File Descriptor table: File descriptor table is the drove of integer array indices that are file descriptors in which elements are pointers to file tabular array entries. One unique file descriptors table is provided in operating organisation for each process.

File Table Entry: File table entries is a construction In-memory surrogate for an open file, which is created when process request to opens file and these entries maintains file position.

Standard File Descriptors: When whatever procedure starts, then that process file descriptors table'due south fd(file descriptor) 0, 1, 2 open automatically, (Past default) each of these 3 fd references file tabular array 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 any character from keyboard, it read from stdin through fd 0 and salve to file named /dev/tty.
Write to stdout => write to fd ane : 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 i.
Write to stderr => write to fd 2 : We see any error to the video screen, it is too from that file write to stderr in screen through fd ii.

I/O Arrangement calls

Basically in that location are total five types of I/O arrangement 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 y'all want to create
  • mode : indicates permissions of new file.

Returns:

  • return first unused file descriptor (generally 3 when showtime create utilise in process because 0, 1, 2 fd are reserved)
  • return -1 when error

How it work in Bone

  • Create new empty file on disk
  • Create file table entry
  • Gear up outset unused file descriptor to point to file tabular array entry
  • Return file descriptor used, -1 upon failure

two. 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 mode ]);        

Parameters

  • Path: path to file which you lot want to use
    • use accented path brainstorm with "/", when you are non work in same directory of file.
    • Employ relative path which is only file name with extension, when yous are work in same directory of file.
  • flags : How you like to use
    • O_RDONLY: read merely, O_WRONLY: write but, O_RDWR: read and write, O_CREAT: create file if it doesn't be, O_EXCL: forestall creation if it already exists

How it works in Os

  • Find the existing file on disk
  • Create file table entry
  • Fix first unused file descriptor to point to file table entry
  • Render 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/n" , fd);

if (fd ==-ane)

{

printf ( "Error Number % d\due north" , errno );

perror ( "Program" );

}

return 0;

}

Output:

fd = 3

3. shut: 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 shut(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 it!
  • Ready element fd of file descriptor table 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 (i);

}

printf ( "closed the fd.\n" );

}

Output:

opened the fd = 3 airtight 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);

go out (0);

}

Output:

fd2 = 3

Here, In this code get-go open() returns 3 because when main process created, then fd 0, one, 2 are already taken by stdin, stdout and stderr. And so first unused file descriptor is 3 in file descriptor table. After that in shut() system call is free it this 3 file descriptor and then afterward set 3 file descriptor as null. And then when we chosen second open(), then first unused fd is also 3. So, output of this plan is 3.

iv. read: From the file indicated past the file descriptor fd, the read() office reads cnt bytes of input into the memory surface area indicated past buf. A successful read() updates the access fourth dimension 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 -1 on signal interrupt

Important points

  • buf needs to point to a valid memory location with length non smaller than the specified size considering of overflow.
  • fd should be a valid file descriptor returned from open() to perform read operation because if fd is Cipher so read should generate mistake.
  • cnt is the requested number of bytes read, while the render value is the actual number of bytes read. Also, some times read organisation call should read less bytes than cnt.

C

#include<stdio.h>

#include <fcntl.h>

int main()

{

int fd, sz;

char *c = ( char *) calloc (100, sizeof ( char ));

fd = open up( "foo.txt" , O_RDONLY);

if (fd < 0) { perror ( "r1" ); exit (1); }

sz = read(fd, c, 10);

printf ( "called read(% d, c, x). returned that"

" %d bytes were read.\n" , fd, sz);

c[sz] = '\0' ;

printf ( "Those bytes are as follows: % s\northward" , c);

}

Output:

chosen read(3, c, 10).  returned that x 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 program?

C

#include<stdio.h>

#include<unistd.h>

#include<fcntl.h>

#include<stdlib.h>

int main()

{

char c;

int fd1 = open( "sample.txt" , O_RDONLY, 0);

int fd2 = open up( "sample.txt" , O_RDONLY, 0);

read(fd1, &c, ane);

read(fd2, &c, one);

printf ( "c = %c\due north" , c);

exit (0);

}

Output:

c = f

The descriptors fd1 and fd2 each take their ain open file table entry, so each descriptor has its ain file position for foobar.txt . Thus, the read from fd2 reads the commencement byte of foobar.txt , and the output is c = f, not c = o.

v. write: Writes cnt bytes from buf to the file or socket associated with fd. cnt should not be greater than INT_MAX (defined in the limits.h header file). If cnt is zero, write() simply returns 0 without attempting any 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

  • return Number of bytes written on success
  • render 0 on reaching stop of file
  • return -1 on error
  • render -i on signal interrupt

Important points

  • The file needs to be opened for write operations
  • buf needs to be at to the lowest degree as long every bit specified by cnt because if buf size less than the cnt then buf will lead to the overflow condition.
  • cnt is the requested number of bytes to write, while the return value is the bodily number of bytes written. This happens when fd have a less number of bytes to write than cnt.
  • If write() is interrupted by a signal, the effect is i of the following:
    -If write() has not written any information 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 it 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, "hullo geeks\n" , strlen ( "hello geeks\n" ));

printf ( "called write(% d, \"hello geeks\\n\", %d)."

" Information technology returned %d\n" , fd, strlen ( "hello geeks\due north" ), sz);

close(fd);

}

Output:

called write(3, "hello geeks\n", 12).  information technology returned eleven

Hither, when y'all see in the file foo.txt after running the code, y'all go a "howdy geeks". If foo.txt file already accept some content in it then write system call overwrite the content and all previous content are deleted and just "hullo geeks" content volition have in the file.

Print "hello world" from the program without use whatsoever 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 world" ;

char buf2[12];

fd[0] = open( "foobar.txt" , O_RDWR);

fd[i] = open up( "foobar.txt" , O_RDWR);

write(fd[0], buf1, strlen (buf1));

write(one, buf2, read(fd[one], buf2, 12));

close(fd[0]);

close(fd[1]);

return 0;

}

Output:

hello globe

In this code, buf1 array's string "howdy globe" is first write in to stdin fd[0] then after that this string write into stdin to buf2 array. Afterward that write into buf2 array to the stdout and print output " howdy earth ".
This article is contributed by Kadam Patel. If yous similar GeeksforGeeks and would like to contribute, yous tin can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your commodity actualization on the GeeksforGeeks chief folio and help other Geeks.
Please write comments if you find anything incorrect, or you desire to share more information almost the topic discussed above.


lombardowithatim.blogspot.com

Source: https://www.geeksforgeeks.org/input-output-system-calls-c-create-open-close-read-write/

0 Response to "Write a C Program That Reads the First 10 Lines of a File and Outputs With Stdout"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel