[英]Removing bytes from File in (C) without creating new File
I have a file let's log
. 我有一个文件让我们
log
。 I need to remove some bytes let's n
bytes from starting of file only. 我需要删除一些字节,仅从文件开头删除
n
个字节。 Issue is, this file referenced by some other file pointers in other programs and may these pointer write to this file log
any time. 问题是,此文件被其他程序中的某些其他文件指针引用,并且可能随时将这些指针写入该文件
log
。 I can't re-create new file otherwise file-pointer would malfunction(i am not sure about it too). 我无法重新创建新文件,否则文件指针将出现故障(我也不确定)。 I tried to google it but all suggestion for only to re-write to new files.
我试图用谷歌搜索它,但所有建议都只重写新文件。 Is there any solution for it?
有什么解决办法吗?
I can suggest two options: 我可以提出两种选择:
tail -F
utility to follow the log contents perpetually. tail -F
实用程序永久跟踪日志内容。 To avoid issues of multiple programs manipulating the same file, your logging code can send logs as messages to a single logging daemon. So... you want to change the file, but you cannot. 所以...您想更改文件,但是不能。 The reason you cannot is that other programs are using the file.
之所以不能,是因为其他程序正在使用该文件。 In general terms, you appear to need to:
一般而言,您似乎需要:
stop all the other programs messing with the file while you change it -- to chop now unwanted stuff off the front; 在更改文件时,请停止所有其他混乱文件的程序-从前面砍掉不需要的东西;
inform the other programs that you have changed it -- so they can re-establish their file-pointers. 告知其他程序您已对其进行了更改-以便他们可以重新建立其文件指针。
I guess there must be a mechanism to allow the other programs to change the file without tripping over each other... so perhaps you can extend that ? 我猜必须有一种机制可以允许其他程序更改文件而不会彼此跳闸...所以也许您可以扩展它? [If all the other programs are children of the main program, then if the children all
O_APPEND
, you have a fighting chance of doing this, perhaps with the help of a file-lock or a semaphore (which may already exist ?). [如果所有其他程序都是主程序的
O_APPEND
,那么如果所有O_APPEND
都是O_APPEND
,则您可能有O_APPEND
的机会这样做,也许是借助文件锁或信号灯(可能已经存在?)。 But if the programs are this intimately related, then @jxh has other, probably better, suggestions.] 但是,如果程序与这些程序密切相关,那么@jxh还有其他(可能更好)的建议。]
But, if you cannot change the other programs in any way, you appear to be stuck, except... 但是,如果您无法以任何方式更改其他程序,则您似乎会卡住,除非...
...perhaps you could try 'sparse' files ? ...也许您可以尝试“稀疏”文件? On (recent-ish) Linux (at least) you can
fallocate()
with FALLOC_FL_PUNCH_HOLE
, to remove the stuff you don't want without affecting the other programs file-pointers. 在(至少)最新的Linux上,您可以使用
FALLOC_FL_PUNCH_HOLE
来fallocate()
,以删除不需要的内容,而不会影响其他程序的文件指针。 Of course, sooner or later the other programs may overflow the file-pointer, but that may be a more theoretical than practical issue. 当然,其他程序迟早可能会溢出文件指针,但这可能比实际问题更具理论性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.