In: Computer Science
****NOTE YOU MUST USE SYSTEM CALL I/O, meaning STANDARD I/O IS NOT ALLOWED THIS MEANS THAT YOU CANT USE fopen, fclose , etc
*****You are ONLY ALLOWED TO USE SYSTEM CALL I/O such as read, write, open and close (System I/O functions)
Write a C program using system call I/O to
a) open an existing text file passed to your program as a command-line argument, then
b) display the content of the file,
c) ask the user what information he/she wants to append
d) receive the info from the user via keyboard
e) append the info received in d) to the end of the file
f) display the updated content of the file.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
int fd1,n;
char buf[1024],buf1[100];
// To open the file rd,wr,append mode
//fd1 = open("a.txt", O_RDWR | O_APPEND);
fd1 = open(argv[1], O_RDWR | O_APPEND);
if (fd1 == -1) {
perror("File cannot be opened");
return EXIT_FAILURE;
}
// To display "Content of File::" on screen
char *s="\nContent of File::\n";
write(1,s,strlen(s)); // write(file descriptor,string address,no_of_bytes to be wriiten)
//File descriptor 1 is standard output.
//To read content of given file and display
n=read(fd1, buf, sizeof(buf)); //no_bytes_read=read(file descriptor,buffer,size);
write(1, buf, n); //write(file descriptor,buffer,no_of_bytes);
//close(fd1); // close
// To display the message on screen
char *s1="\nEnter the string to append to the file\n";
write(1,s1,strlen(s1));
// To read string from user
read(0,buf1,100); //File descriptor 0 is standard input(key board).
//open the file in append mode to write the string at the end of file
//fd1 = open("a.txt",O_WRONLY | O_APPEND);
write(fd1, buf1, strlen(buf1));
close(fd1); //close file descriptor
//To display message
char *s3="\nContent of File after appending::\n";
write(1,s3,strlen(s3)); // write(file descriptor,string address,no_of_bytes to be wriiten)
//File descriptor 1 is standard output.
//To read content of given file and display
//fd1 = open("a.txt",O_RDONLY);
fd1 = open(argv[1],O_RDONLY);
n=read(fd1, buf, sizeof(buf)); //no_bytes_read=read(file descriptor,buffer,size);
write(1, buf, n); //write(file descriptor,buffer,no_of_bytes);
close(fd1); // close
return 0;
}
int open (char* fileName, int mode [, int permissions])
O_RDONLY Open for reading only. O_WRONLY Open for writing only. O_RDWR Open for reading and writing.
O_APPEND: Position the file pointer at the end of the file before each write ().
ssize_t read (int fd, void* buf, size_t count)
ssize_t write (int fd, void* buf, size_t count)
int close (int fd)