Working with Files

The open() Function

#include <fcntl.h>  // file control, contains some contants
#include <unistd.h> // contains open
#include <stdio.h>

int main(){
    
    // create a file descriptor (an int reference for a file)
    // file descriptors 0, 1, and 2 are stdin, stdout, and stderr 
    // use O_WRONLY to open to edit
    // use O_CREAT to create the file if it doesn't exist
    // use O_TRUNC to erase the contents of the file before writing (O_APPEND for just appending)
    // we use bitwise | to apply multiple properties
    // we use 0644 for the file permissions (the leading 0 makes it an octal number)
    // recall we understand 644 to mean owner can read and write, others can read
    int fd = open("hello.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    printf("File Descriptor: %d\n", fd); // notice it is not 0, 1, or 2
    
    if (fd < 0){
        // this means we have an error
        perror("Error with open() function");
        return 1;
    }

    const char msg[] = "These are the contents.\n";

    // write to the file
    // give file descriptor, message, and number of bytes
    write(fd, msg, sizeof(msg) - 1); // size - 1 bc strings end with \0, a null terminator

    // close to release the file descriptor
    close(fd);
    return 0;
}

The fopen() Function

#include <stdio.h>

// note: we will use fopen() here instead of open()
// fopen() is easier to work with

int main(){

    // fopen is part of stdio
    // params: filename, mode
    // filename is the path to the file
    // mode is r for read, w for write, a for append, amongst others
    // returns NULL on error
    
    FILE *filePtr = fopen("hello.txt", "r");

    // check if the file exists
    if (filePtr == NULL){
        perror("");
        return 0;
    }

    // operate on file contents here (not shown)
    
    // close the file
    fclose(filePtr);

    return 0;
}