DEV Community

mikkel250
mikkel250

Posted on

Writing to files in C

Overview

Like their "get" complements, there are a number of functions in the standard library for writing to a file, those that write individual characters, and others that write strings. Like their complements, these functions are intended to work in conjunction with files that have been already been opened by fopen(), which returns a pointer, and thus take a file pointer as an argument.

Writing characters to files with "file put character" function fputc()

The fgetc(), which I read in my mind as "file put character", takes two arguments: the ASCII code of the character to be written (an integer), and a pointer to the file to which the character will be written. It writes a single character to the file each time it is called.
The function returns the character that was written. If an error occurs, EOF is returned instead.

// Syntax
char *fputc(int characterToWrite, FILE *pointerToFileToBeRead);
Enter fullscreen mode Exit fullscreen mode

The example below demonstrates basic usage.

#include <stdio.h>

int main()
{
  // pointer to the file to be read
  FILE *filePointer = NULL;

  // declare an int to hold the value of the current character to write
  int characterToWrite;

  // open the file to be read, in read-write mode "w+"
  filePointer = fopen("test-fputc.txt", "w+");

  // check the result of opening the file for errors
  if (filePointer == NULL)
  {
    // perror displays the system error message after whatever text is in the parentheses
    perror("Error: ");
    return (-1);
  }

  // will write lowercase a-z
  for(characterToWrite = 97; characterToWrite <= 122; characterToWrite++)
  {
    fputc(characterToWrite, filePointer);
  }

  // close the file
  fclose(filePointer);

  // set the pointer to null to reset it and free the memory
  filePointer = NULL;

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Another trick that can be employed is the use of the "ASCII to integer" atoi() function instead of working directly with the ASCII numbers. Put the character to be written in single quotes as the argument of atoi(), which will convert the ASCII character to to corresponding integer in the ASCII table.

for(characterToWrite = atoi('a'); characterToWrite <= atoi('z'); characterToWrite++)
  {
    fputc(characterToWrite, filePointer);
  }
Enter fullscreen mode Exit fullscreen mode

There is also a putc() for writing characters to files, but may be implemented differently (as a macro) in the standard library, and will not be covered.

Writing strings to files with "file put string" - fputs()

To write an entire string to a file, use fputs(), which is more efficient than writing a character at a time. It works in much the same way as the fputc() function, but it takes a pointer to a character array (aka string) as the first argument, and the a pointer to the file as the second argument.

It will write until it encounters a null (string) terminator character \0.
Note, however, that the function itself will not automatically add the \0 character to the file. You must remember to explicitly add a terminator, either by using fputc('\0'), or adding a newline character at the end, otherwise it can complicate reading back variable-length strings from a file that has been written using this function.

On failure EOF is returned from the function.

Syntax:

fputs(char *stringToWrite, FILE *fileToBeRead);
Enter fullscreen mode Exit fullscreen mode

How it is used:

#include <stdio.h>

int main()
{
  // create the pointer to the file to be read
  FILE *filePointer = NULL;

  filePointer = fopen("test-fputs.txt", "w+);

  // check there is no error opening the file
  if (filePointer == NULL)
  {
    perror("Error: ");
    return(-1);
  }

  fputs("Testing the fputs function", filePointer);
  fputs("This is the second string to write to a file.", filePointer);

  fclose(filePointer);
  filePointer = NULL;

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Writing formatted input to a file

To write formatted input to a file, there is a an fprintf() function that works much like printf() for files. The difference is that it takes as the first argument the file to which the input will be written. The other arguments are a list of any number of formats to write. It returns the number of characters written. If the operation fails, it will return a negative number.

The syntax is:

int fprintf(FILE *fileToReceiveInput, firstFormatSpecifier, secondFormatSpecifier, ...etc);
Enter fullscreen mode Exit fullscreen mode

Example of use:

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

int main()
{

  // create a pointer to the file that will be opened
  FILE *filePointer = NULL;

  // assign the pointer to the result of opening the file with fopen()
  filePointer = fopen("test-fprintf.txt", "w+");

  // check there are no errors when opening the file
  if (filePointer != NULL)
  {
    perror("Error: ");
    return(-1);
  }

  // write the formatted data to the file
  fprintf("%s %s %s %s %d", "Happy", "New", "Year! ", "It's ", 2020);

  fclose(filePointer);
  filePointer = NULL;

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

When the above is run, the terminal won't show any output, so check the file to make sure that the data has been written to the file.
If you want to add a line feed to the strings, include it manually in the string with the format specifiers.

  fprintf("%s %s %s\n %s %d", "Happy", "New", "Year! ", "It's ", 2020);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)