0% found this document useful (0 votes)
22 views2 pages

Ques 2

The document contains 5 code examples demonstrating basic file I/O operations in C including opening, writing, and reading files using functions like open, write, read, and close.

Uploaded by

thiru252627
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views2 pages

Ques 2

The document contains 5 code examples demonstrating basic file I/O operations in C including opening, writing, and reading files using functions like open, write, read, and close.

Uploaded by

thiru252627
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

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;
}

You might also like