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