Experiment 6
Title: Implementation of various operations on Files (Create, Open, Read, Write, Append, Fstat,
Dup etc.)
Aim: To Learn about various operations on Files (Create, Open, Read, Write, Append, Fstat, Dup
etc.)
Theory: write theory about various operations on Files (Create, Open, Read, Write, Append,
Fstat, Dup etc.)
(here write the use of each operation then syntax with short explanation)
Problem Statement: Implement various operations on Files (Create, Open, Read, Write,
Append, Fstat, Dup etc.)
Conclusion
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
// Create a new file
int fd = open("[Link]", O_CREAT | O_WRONLY, 0644);
if (fd == -1) {
perror("open");
exit(1);
// Write some data to the file
char *data = "This is some data to be written to the file.";
int bytes_written = write(fd, data, strlen(data));
if (bytes_written == -1) {
perror("write");
exit(1);
// Close the file
close(fd);
// Open the file for reading
fd = open("[Link]", O_RDONLY);
if (fd == -1) {
perror("open");
exit(1);
// Read some data from the file
char buffer[1024];
int bytes_read = read(fd, buffer, sizeof(buffer));
if (bytes_read == -1) {
perror("read");
exit(1);
// Print the data that was read
printf("%s\n", buffer);
// Close the file
close(fd);
// Append some data to the file
fd = open("[Link]", O_APPEND | O_WRONLY);
if (fd == -1) {
perror("open");
exit(1);
}
// Write some data to the file
data = "This is some data to be appended to the file.";
bytes_written = write(fd, data, strlen(data));
if (bytes_written == -1) {
perror("write");
exit(1);
// Close the file
close(fd);
// Get the file status
struct stat st;
if (stat("[Link]", &st) == -1) {
perror("stat");
exit(1);
// Print the file size
printf("File size: %ld bytes\n", st.st_size);
// Duplicate the file descriptor
int fd2 = dup(fd);
if (fd2 == -1) {
perror("dup");
exit(1);
// Close the original file descriptor
close(fd);
// Write some data to the duplicated file descriptor
data = "This is some data to be written to the duplicated file descriptor.";
bytes_written = write(fd2, data, strlen(data));
if (bytes_written == -1) {
perror("write");
exit(1);
// Close the duplicated file descriptor
close(fd2);
return 0;