7. File Access

Introduction

Opening a File

Opening Files with Unusual Filenames

Expanding Tildes in Filenames

Making Perl Report Filenames in Errors

//------------------------------------------------------------------
#include <stdio.h>
#include <string.h> // strerror()
#include <errno.h> // errno

...

FILE * fp;

if( (fp = fopen(filename, mode)) == NULL )
  fprintf( stderr, "Couldn't open %s for reading : %s\n",
           filename,
           strerror(errno) );

...

Creating Temporary Files

//------------------------------------------------------------------
#include <stdio.h> // tmpfile()

...

FILE * file;

// /!\ the temporary filename isn't accessible
file = tmpfile(); 

...

//------------------------------------------------------------------
#include <stdio.h> // remove()
#include <stdlib.h> // mkstemp()

...

int fd;
char template[20];

strcpy( template, "tmp/XXXXXX" );
fd = mkstemp( template );

if( fd < 0 ) {
  perror( mkstemp );
  exit( 1 );
}

remove( template );

// now go on to use the file ...

...

//------------------------------------------------------------------
#include <stdio.h> // tempnam()
#include <stdlib.h>
#include <unistd.h> // unlink()
#include <fcntl.h> // open()
#include <sys/stat.h> 
#include <sys/types.h>

...

char * tmpname = NULL;
int fd;

while(1) {
  tmpname = tempnam( NULL, NULL );
  if( tmpname == NULL ) {
    perror( "tempname" );
    exit(1);
  }

  // is another process creating a temporary file at the same moment?
  // we don't know.
  // => we have to ensure an exclusive open
  fd = open( tmpname, O_CREAT | O_EXCL | O_RDWR, 0600 );

  // temporary file will be destroy on close() call
  unlink( tmpname );

  free( tmpname );
  if( fd < 0 )
    perror( "open" );
  else
    break;
}

// now go on to use the file ...

...

Storing Files Inside Your Program Text

Writing a Filter

Modifying a File in Place with Temporary File

Modifying a File in Place with -i Switch

Modifying a File in Place Without a Temporary File

Locking a File

Flushing Output

Reading from Many Filehandles Without Blocking

Doing Non-Blocking I/O

Determining the Number of Bytes to Read

Storing Filehandles in Variables

Caching Open Output Filehandles

Printing to Many Filehandles Simultaneously

Opening and Closing File Descriptors by Number

Copying Filehandles

Program: netlock

Program: lockarea