C++底层对文件操作的一个算法,来大神
现在有2个需求:
1.一个文件在1s内,被操作次数可能超过2次(这里操作文件的可能不只一个进程),只返回最后一次的操作;
2.一个程序对一个文件操作,如果1s内超过2次,也只返回最后一次的操作;
现在没啥思路,有没有大神路过的,请指点1,2;
[解决办法]
标志位,共享内存。多进程操作,把操作结果共享
[解决办法]
只返回最后一次的操作 是指什么啊
是操作成功还是失败
还是操作之后的文件内容啊
[解决办法]
mode must be one of the following manifest constants, which are defined in LOCKING.H:
_LK_LOCK
Locks the specified bytes. If the bytes cannot be locked, the program immediately tries again after 1 second. If, after 10 attempts, the bytes cannot be locked, the constant returns an error.
_LK_NBLCK
Locks the specified bytes. If the bytes cannot be locked, the constant returns an error.
_LK_NBRLCK
Same as _LK_NBLCK.
_LK_RLCK
Same as _LK_LOCK.
_LK_UNLCK
Unlocks the specified bytes, which must have been previously locked.
Multiple regions of a file that do not overlap can be locked. A region being unlocked must have been previously locked. _locking does not merge adjacent regions; if two locked regions are adjacent, each region must be unlocked separately. Regions should be locked only briefly and should be unlocked before closing a file or exiting the program.
Example
/* LOCKING.C: This program opens a file with sharing. It locks
* some bytes before reading them, then unlocks them. Note that the
* program works correctly only if the file exists.
*/
#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 );
}
Output
No one can change these bytes while I'm reading them
30 bytes read: /* LOCKING.C: This program ope
Now I'm done. Do what you will with them
File Handling Routines
See Also _creat, _open
[解决办法]
还有,啥叫扫描文件?
是指遍历目录下的文件还是遍历文件中的内容
不要自己省略上下文语境....
[解决办法]
你这个问题我最近有一个部分类似的场景
你了解下我的做法
我有一个写文件类似于log的操作,比较费时,但是我调用的频率可能很高,一秒几万次的样子。
为了不住阻塞调用的线程,我把这个写操作post到另一个线程去写,(因为只有一个线程,所以依次执行写操作即可,写的内容里面有很多前后覆盖的也没关系)。
后来发现这么处理,因为写文件的次数太多,导致写文件的线程在程序退出时要等很久才能完全退出
于是采用了以下的策略
设置一个变量 bPost 代表是否有已经post,但未处理的写请求。
每一次请求写操作,检查bPost的值,若真,直接返回。若假 则post,置bPost为真。
每一次执行写操作,置bPost为假,实际写文件。
注意bPost需要原子变量或者用锁同步。
当时我实测1000次请求,可以忽略掉996次。