1).
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *ent;
if ((dir = opendir(".")) != NULL) {
while ((ent = readdir(dir)) != NULL) {
printf("%s\n", ent->d_name);
}
closedir(dir);
} else {
perror("Error opening directory");
return 1;
}
return 0;
}
2).
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// Child process
printf("This is the child process.\n");
} else if (pid > 0) {
// Parent process
printf("This is the parent process.\n");
} else {
perror("Fork failed");
return 1;
}
return 0;
}
3).
#include <stdio.h>
#include <fcntl.h>
int main() {
int fileDescriptor = open("example.txt", O_RDONLY);
if (fileDescriptor == -1) {
perror("Error opening file");
return 1;
}
printf("File opened successfully. File Descriptor: %d\n", fileDescriptor);
close(fileDescriptor);
return 0;
}
4).
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main() {
int fileDescriptor = open("example.txt", O_WRONLY | O_CREAT, S_IRUSR |
S_IWUSR);
if (fileDescriptor == -1) {
perror("Error opening or creating file");
return 1;
}
const char *message = "Hello, Write System Call!";
write(fileDescriptor, message, strlen(message));
printf("Data written to file successfully.\n");
close(fileDescriptor);
return 0;
}
5).
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fileDescriptor = open("example.txt", O_RDONLY);
if (fileDescriptor == -1) {
perror("Error opening file");
return 1;
}
char buffer[100];
ssize_t bytesRead = read(fileDescriptor, buffer, sizeof(buffer));
if (bytesRead == -1) {
perror("Error reading from file");
close(fileDescriptor);
return 1;
}
printf("Read from file: %s\n", buffer);
close(fileDescriptor);
return 0;
}