Home » Programming Languages » C Programs » C code for safe read and write from a file

C code for safe read and write from a file

Below functions make sure we are safely and completely reading and writing from a file pointer fd, opened on a specific file.

int safe_read( int fd, void *buf, size_t len )
{
        int n;
        size_t sum = 0;
        char  *off = (char *) buf;
 
        while( sum < len )
        {
                if( ! ( n = read( fd, (void *) off, len - sum ) ) )
                {
                        return( 0 );
                }
                if( n < 0 && errno == EINTR ) continue;
                if( n < 0 ) return( n );
 
                sum += n;
                off += n;
        }
        return( sum );
}

int safe_write( int fd, void *buf, size_t len )
{
        int n; 
        size_t sum = 0;
        char  *off = (char *) buf;
 
        while( sum < len )
        {
                if( ( n = write( fd, (void *) off, len - sum ) ) < 0 )
                {
                        if( errno == EINTR ) continue;
                        return( n );
                }
 
                sum += n;
                off += n;
        }
 
        return( sum );
}

Leave a Comment