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

Program

This document presents a simple C program that demonstrates the use of basic UNIX file APIs including open(), read(), write(), close(), and creat(). The program creates a file, writes a string to it, reopens the file for reading, and then prints the content read from the file. Error handling is included for each file operation.

Uploaded by

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

Program

This document presents a simple C program that demonstrates the use of basic UNIX file APIs including open(), read(), write(), close(), and creat(). The program creates a file, writes a string to it, reopens the file for reading, and then prints the content read from the file. Error handling is included for each file operation.

Uploaded by

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

Simple C program that demonstrates how to use basic UNIX file APIs: open(), read(), write(),

close(), and creat()

#include <stdio.h>

#include <fcntl.h> // for open(), O_* constants

#include <unistd.h> // for read(), write(), close()

#include <string.h> // for strlen()

int main() {
int fd;

char *filename = "[Link]";


char *text = "Hello, UNIX file APIs!\n";

char buffer[100];

ssize_t bytes_read;

// Create a new file or truncate if it already exists

fd = creat(filename, 0644); // equivalent to open() with O_CREAT | O_WRONLY | O_TRUNC


if (fd < 0) {

perror("creat");

return 1;

// Write to the file

if (write(fd, text, strlen(text)) < 0) {

perror("write");
close(fd);

return 1;

// Close the file

close(fd);
// Reopen the file for reading

fd = open(filename, O_RDONLY);

if (fd < 0) {

perror("open");
return 1;

// Read from the file

bytes_read = read(fd, buffer, sizeof(buffer) - 1);

if (bytes_read < 0) {

perror("read");

close(fd);

return 1;
}

// Null-terminate and print the content

buffer[bytes_read] = '\0';

printf("Read from file: %s", buffer);

// Close the file

close(fd);

return 0;
}

You might also like