C interview question:
How do I write code that reads data at memory location specified by segment and offset?
Answer:
Use peekb( ) function. This function returns byte(s) read from specific
segment and offset locations in memory. The following program
illustrates use of this function. In this program from VDU memory we
have read characters and its attributes of the first row. The
information stored in file is then further read and displayed using
peek( ) function.
main( )
{
char far *scr = 0xB8000000 ;
FILE *fp ;
int offset ;
char ch ;
if ( ( fp = fopen ( "scr.dat", "wb" ) ) == NULL )
{
printf ( "\nUnable to open file" ) ;
exit( ) ;
}
// reads and writes to file
for ( offset = 0 ; offset < 160 ; offset++ )
fprintf ( fp, "%c", peekb ( scr, offset ) ) ;
fclose ( fp ) ;
if ( ( fp = fopen ( "scr.dat", "rb" ) ) == NULL )
{
printf ( "\nUnable to open file" ) ;
exit( ) ;
}
// reads and writes to file
for ( offset = 0 ; offset < 160 ; offset++ )
{
fscanf ( fp, "%c", &ch ) ;
printf ( "%c", ch ) ;
}
fclose ( fp ) ;
}