c > files > file operations

File Operations

Why do you think we need to be able to access files in C? (Tap/click an answer below)

File pointer

In C, we need to create a pointer to the file we want to interact with. The fopen() helps us to create this file pointer. It accepts two arguments - the path to the file we want to use and the access mode. There are many access modes, the most common being write, read and append.

We need to use the fclose() function in order to close the file.

FILE* fp = fopen("my_file.txt",w);// or r or a
// write to or read from the file

Writing to a file

We can use fprintf() in order to add text to a file in the same way that we add text to the console using printf():

#include <stdio.h>

int main(){
    char name[] = "John Doe";
    int age = 13;
    FILE* fp = fopen("my_file.txt","w");
    fprintf(fp,"Hello how are you?\n");
    fprintf(fp,"My name is %s\n",name);
    fprintf(fp,"I am %d years old\n",age);
    return 0;

↗ Open 📋 Copy c/files/writing_to_a_file.c

For the write mode, there is no need to create the file if it does not already exist. It should be noted that if the file already exists, then the contents of that file will be erased when we open it in write mode.

Is the file automatically created when using fopen() in write mode? (Tap/click an answer below)

Reading from a file

We use the fscanf() function to read the contents of a file. We instruct the computer to read using a while loop, with the end condition being when the end of the file is encountered.

#include <stdio.h>

int main(){
    // string variable to store temporary data
    char buffer[100];
    FILE* fp = fopen("my_file.txt","r");
    // loop through the contents until the end of the file is found
        // for every iteration, buffer is used to store the string detected
    return 0;

↗ Open 📋 Copy c/files/reading_from_a_file.c

Why do the printed lines not match the lines of the file but instead appear to be word by word? (Tap/click an answer below)