Strumenti Utente

Strumenti Sito


matematica:asd:asd_21:mmap
  #include <iostream>

  /* servono per mmap */
  #include <sys/mman.h>
  #include <sys/stat.h>

  using namespace std;

  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++ )
      cout << text[i];
    cout << endl;
  
    /* modifica il file */
    text[0] = 'X';
  
    /* stampa di nuovo il file */
    for( i=0; i < n; i++ )
      cout << text[i];
    cout << endl;

    /* chiudi il file */
    fclose( fd );
  
    return 0;
  }
matematica/asd/asd_21/mmap.txt · Ultima modifica: 05/05/2022 alle 09:47 (2 anni fa) da Roberto Grossi