File input / output

This is an introductory explanation of C language file input / output. As for the file input / output method, we will introduce the method of reading and writing one character at a time, the method of reading and writing several bytes at a time, and the method of reading and writing the entire file.

Open the file

In order to input / output a file, you must first open the file.

You can use the fopen function to open the file. You can use it by reading the stdio.h header.

FILE * fopen (const char * file_name, const char * mode);

The first argument is the filename of the file you want to open. The second argument is the mode. If the file is opened successfully, a value of "FILE * type" representing the file stream is returned.

List of modes

A list of modes.

Mode Behavior
r Read (error if there is no file)
w Write (create new if there is no file)
a Additional write (create new if there is no file)
r + Read and write (error if there is no file)
w + Read and write (create new if there is no file)
a + Read and add write (create new if there is no file)

Writing means that the contents of the file are cleared and you are writing with new contents. Additional write means to add to the end of the file and write.

The above modes can be combined with "b" which means binary mode.

br
bw

The default behavior is to open in text mode, and in the case of Windows, the line feed characters "CR" and "LF" contained in the file are replaced with "\ n".

In binary mode, this replacement is not possible.

Close the file

When you have finished inputting and outputting the file, you need to close the file.

You can close the file with the fclose function. You can use it by reading the stdio.h header.

int fclose (FILE * fp);

The argument is the file stream of the file you want to close. Returns 0 if the file close is successful, EOF if it is an error. The buffer is flushed when the file is closed. A buffer is a memory area that temporarily stores write data. Flash means writing out the data in the buffer.

Read one character from a file

To read a single character from a file, use the fgetc function.

The fgetc function is a function that reads one character from a file. You can use it by reading the stdio.h header.

#include <stdio.h>
int fgetc (FILE * fp);

Reads one character from the file stream and returns the read character. If the end of the file is reached, EOF is returned.

Read character by character from a file

This is a sample to read one character at a time from a file. This is a sample of the fgetc function. Open the file in read mode with the fopen function and use the fgetc function one character at a time. It is read, output to standard output, and the file is closed with the fclose function.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main (void) {
  
  // Open the file in read mode
  const char * in_file = "input.txt";
  FILE * in_fp = fopen (in_file, "r");
  if (in_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", in_file);
    exit (1);
  }
  
  // Read and output to standard output
  int32_t ch;
  while (ch = fgetc (in_fp)) {
    // If EOF is returned
    if (ch == EOF) {
      // Check if it is the end of the file
      if (feof (in_fp)) {
        break;
      }
    }
    fputc (ch, stdout);
  }
  
  // Close the file with the fclose function
  fclose (in_fp);
}

It is an input file "input.txt".

Hello
World!

This is the output result.

Hello
World!

Export to file

Let's set the output destination of the above sample to "output.txt".

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main (void) {
  
  // Open the file in read mode
  const char * in_file = "input.txt";
  FILE * in_fp = fopen (in_file, "r");
  if (in_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", in_file);
    exit (1);
  }

  // Open the file in write mode
  const char * out_file = "output.txt";
  FILE * out_fp = fopen (out_file, "w");
  if (out_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", out_file);
    exit (1);
  }
  
  // Read and output to file
  int32_t ch;
  while (ch = fgetc (in_fp)) {
    // If EOF is returned
    if (ch == EOF) {
      // Check if it is the end of the file
      if (feof (in_fp)) {
        break;
      }
    }
    fputc (ch, out_fp);
  }
  
  // Close the file with the fclose function
  fclose (in_fp);
  fclose (out_fp);
}

Read / write in units of several bytes

This is a sample to read and write in units of several bytes. fread function reads several bytes from the input file, and fwrite function Writes a few bytes to the output file.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main (void) {
  
  // Open the file in read mode
  const char * in_file = "input.txt";
  FILE * in_fp = fopen (in_file, "r");
  if (in_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", in_file);
    exit (1);
  }

  // Open the file in write mode
  const char * out_file = "output.txt";
  FILE * out_fp = fopen (out_file, "w");
  if (out_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", out_file);
    exit (1);
  }

  // Read and output to another file
  while (1) {
    
    // Read 4 bytes at a time
    char buffer [16];
    int32_t read_unit = 1;
    int32_t read_count = 4;
    size_t real_read_count = fread (buffer, read_unit, read_count, in_fp);
    
    // Write 4 bytes at a time
    fwrite (buffer, read_unit, real_read_count, out_fp);
    
    if (real_read_count <read_count) {
      break;
    }
  }
  
  // Close the file with the fclose function
  fclose (in_fp);
}

It is an input file "input.txt".

Hello
World!

The output file is "output.txt".

Hello
World!

Read and write the entire file

This is a sample to read and write the entire file. Use the ftell function and the fseek function to get the size of the file. , calloc function to allocate memory, and fread function to fill the entire file. It is read and written with the fwrite function.

The file is open in binary mode when reading and writing.

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main (void) {
  // Open the file
  const char * in_file = "input.txt";
  FILE * in_fp = fopen (in_file, "rb");
  if (in_fp == NULL) {
    fprintf (stderr, "Can't open file%s at%s line%d\n", in_file, __FILE__, __LINE__);
    exit (1);
  }

  // Open the file in write mode
  const char * out_file = "output.txt";
  FILE * out_fp = fopen (out_file, "wb");
  if (out_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", out_file);
    exit (1);
  }

  // Move the position specifier to the end of the file
  fseek (in_fp, 0, SEEK_END);
  
  // Get the position of the end of the file. This will be phi size.
  size_t file_size = (int32_t) ftell (in_fp);
  
  // Allocate memory
  char * buffer = calloc (file_size + 1, sizeof (char));

  // Move the position specifier to the beginning of the file
  fseek (in_fp, 0, SEEK_SET);
  
  // Read the file
  size_t read_count = fread (buffer, sizeof (char), file_size, in_fp);
  if (read_count! = file_size) {
    fprintf (stderr, "Can't read file%s at%s line%d\n", in_file, __FILE__, __LINE__);
    exit (1);
  }
  
  // Write to output file
  fwrite (buffer, sizeof (char), file_size, out_fp);
  
  // Close the file
  fclose (in_fp);
}

It is an input file "input.txt".

Hello
World!

The output file is "output.txt".

Hello
World!

How to read from a file line by line?

In the C language standard, there is no easy way to read from a file, line by line. You can do it with some ingenuity, but you will need to manage your own memory. Many of the things posted on the net use a fixed array and there is a possibility that the line will be cut off in the middle.

Currently (listed on June 16, 2021), the memory capacity has also increased, so it's easier to read everything and then process it.

If you want to read line by line, you may want to use a programming language that is good at text processing.

Associated Information