论坛 题目:
有一个比较大的文件,分批读取,每次读取一批存入内存(每一批的长度是固定的)。问题是,读完一批,需要关闭文件,从而让其他的函数写这个文件。再打开它时,能定位到下一批吗?请教大家,谢谢!
用锁
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/locking.h>
#include <share.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
void main( void )
{
int fh, numread;
char buffer[40];
/* Quit if can't open file or system doesn't
* support sharing.
*/
fh = _sopen( "locking.c", _O_RDWR, _SH_DENYNO,
_S_IREAD | _S_IWRITE );
if( fh == -1 )
exit( 1 );
/* Lock some bytes and read them. Then unlock. */
if( _locking( fh, LK_NBLCK, 30L ) != -1 )
{
printf( "No one can change these bytes while I'm reading them\n" );
numread = _read( fh, buffer, 30 );
printf( "%d bytes read: %.30s\n", numread, buffer );
lseek( fh, 0L, SEEK_SET );
_locking( fh, LK_UNLCK, 30L );
printf( "Now I'm done. Do what you will with them\n" );
}
else
perror( "Locking failed\n" );
_close( fh );
}