Warning
This page is located in archive. Go to the latest version of this course pages. Go the latest version of this page.

Lab 06 - File Handling

Writing to a file

We can write to a file in the following manner:

# include <stdio.h>
# include <string.h>

int main()
{
    FILE *pFile;

    char myString[] = "my string goes here";

    pFile = fopen("myText.txt", "w");
    if(pFile == NULL)
    {
        printf("Failed to open file\n");
    }
    else
    {
        fputs(myString, pFile);
        fclose(pFile);
    }

    return 0;
}

We create a pointer to a file object, and open the file for writing. Note that the “w” parameter denotes that the file will be written to (and therefore created if it does not exist). Alternatives modes exist, such as “a” for appending to the end of an existing file, and also for reading the file which we will see later.

We make sure the file is open, and then use fputs to write our string into the file, before finally closing it.

Reading from a file

The process of reading a file is structurally very similar:

# include <stdio.h>
# include <string.h>

int main()
{
    FILE *pFile;

    char myString[50];

    pFile = fopen("myText.txt", "r");
    if(pFile == NULL)
    {
        printf("Failed to open file\n");
    }
    else
    {
        while(fgets(myString, 50, pFile) != NULL)
        {
            printf("%s", myString);
        }
        fclose(pFile);
    }

    return 0;
}

We again open the file (this time in “r” mode), and check that it has been opened properly again. We use fgets to read data into a buffer. This will keep reading data into the buffer until one of the following conditions are met:

  • End of file
  • Buffer is full
  • End of line

In this case, we simply print the resulting string, and then close the file. As we are in a loop, we the printing will happen repeatedly for each line until the end.

Tasks

This lab we will build an address book system.

Write a program which will allow users to create user profiles (first name, surname, age, etc). The program will allow the user to save the current data to a file. The program can also open a file to read data from a previous time.

courses/be5b99cpl/labs/lab06.txt · Last modified: 2022/11/02 10:51 by brouggeo