File Operations

2-minute read
Table of Contents

What do you think?

1) Why do you think we need to be able to access files in C?

  1. To repeat a section of code for a specific number of times
  2. To make our code look fancy when people try to read it
  3. To flex on our friends
  4. To store data after the program has finished running

File pointers

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
fclose(fp);

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);
    fclose(fp);
    return 0;
}
writing-to-a-file.c
Copy

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.


What do you think?

2) Is the file automatically created when using fopen() in write mode?

  1. Yes
  2. No

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
    while(fscanf(fp,"%s",buffer)!=EOF){
        // for every iteration, buffer is used to store the string detected
        printf("%s\n",buffer);
    }
    return 0;
}
reading-from-a-file.c
Copy

What do you think?

3) Why do the printed lines not match the lines of the file but instead appear to be word by word?

  1. The format specifier %s is for every character up to the space character
  2. The format specifier %s is for every character up to the curly braces
  3. The format specifier %s is for every character up to the newline character

Support us via BuyMeACoffee

Resources

Here are some resources we recommend for you to use along with this lesson: