22 BPS1110 Oslab 2
22 BPS1110 Oslab 2
NAME: SAHANA R
REG NO. : 22BPS1110
LAB SLOT: L23+24
AIM:
- Create System Call: To create a new file or open an existing file.
- Write System Call: To write data to a file.
- Read System Call: To read data from a file.
To perform the above system calls and to verify the output.
Source Code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd;
fd = creat("file.txt", S_IRWXU); // Create a file
if (fd == -1) {
printf("Error creating the file\n");
} else {
printf("File created successfully\n");
}
close(fd); // Close the file
return 0;
}
Output:
If successful, the create system call returns a non-negative integer known as a file
descriptor, representing the newly created file. Returns -1 on failure.This file descriptor
is used in subsequent operations on the file. After the create system call , we have
create a new file named file.text in the required directory
2. WRITE SYSTEM CALL:
Source Code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd;
fd = open("file.txt", O_WRONLY | O_CREAT, S_IRWXU); // Open the file for writing or
create it if it doesn't exist
if (fd == -1) {
printf("Error opening/creating the file\n");
} else {
char buf[] = "Hello, World!, This is Sahana 22BPS1110";
ssize_t bytesWritten = write(fd, buf, sizeof(buf) - 1); // Write to the file
if (bytesWritten == -1) {
printf("Error writing to the file\n");
} else {
printf("Data written to file successfully\n");
}
}
close(fd); // Close the file
return 0;
}
Output:
Result and Explanation of Output :
Returns a file descriptor if successful, which can be used for subsequent operations on
the file. Returns -1 on failure, and `errno` is set to indicate the error. Here in the file the
following contents are written successfully “Hello , World!, This is Sahana 22BPS1110”.
Source Code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFSIZE 1024
int main() {
int fd;
char buf[BUFSIZE];
Output:
Returns the number of bytes read, which can be less than the requested size. Returns 0
at the end of the file, and -1 on failure with `errno` indicating the error. It successfully
reads the content of the file which is “Hello , World!, This is Sahana 22BPS1110”.