Strumenti Utente

Strumenti Sito


matematica:asd:asd_14:mmap
#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>

typedef unsigned char byte;

#define ERR(msg)  {fprintf(stderr, "%s\n", msg); exit(2);}

int main( int argc, char **argv ){
  int n, i;
  byte *text;

  FILE *fd;
  struct stat stat_buffer;
  
  /* apriamo il file in lettura e scrittura */
  fd = fopen( argv[1], "r+w" );
  if ( fd == NULL )
    ERR("errore di aperture del file");
  /* lunghezza del file in byte */
  if (fstat( fileno(fd), &stat_buffer) == -1)
    ERR("errore nella fstat");
  n = stat_buffer.st_size;

  /* mmap per associare text all'intero file in fd */
  text = (byte *)mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(fd), 0);
  if ( text == NULL )
    ERR( "errore nella mmap" );
  /* stampa il file */
  for( i=0; i < n; i++ )
    printf( "%c", text[i] );
  printf( "\n" );

  /* modifica il file */
  text[0] = 'X';

  /* chiudi il file */
  fclose( fd );

  return 0;
}
matematica/asd/asd_14/mmap.txt · Ultima modifica: 11/03/2015 alle 16:30 (10 anni fa) da Roberto Grossi

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki