读取(打开)文件时如何阻止文件 [英] How to block file when you reading (fopen) it

查看:72
本文介绍了读取(打开)文件时如何阻止文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在读取文件时(通过fopen或在Linux中打开文件)阻止文件,以防止在读取过程中进行任何修改?

How to block file when you reading it (by fopen or open in linux), to prevent any modifications during reading?

我拥有:1个包含数据的文件;我想从函数中读取数据,所以我使用fopen():

What i have: 1 file with data; I want to read data from it in my function, so i use fopen():

FILE * file = fopen(fileName, r);
现在,我需要一些东西来阻止我的文件-任何(或只有当前用户的作为变体)另一个进程在对其功能允许之前,不能对其具有任何访问权限(或仅对其进行变体修改)

FILE *file = fopen(fileName, "r"); Now i need something to block my file - any (or only current user's as variant) another process mustn't have any access (or only modify it as variant) to it until my function will allow them to do it

我想,我可以为它们使用set chmod标志并在下班后将其设置回去;
或使用带有特殊标志参数的open()函数,但这不是可取的,因为我想在函数中使用fgets();

I suppose, i can do that using set chmod flags for them and setting them back after work; Or using open() function with special flags arguments, but it's not desirable because i would like to work with fgets() in function;

有没有

推荐答案

是的,您可以使用羊群来执行此操作。但是,由于要使用 fopen 而不是 open 打开文件,因此需要首先获取文件使用 fileno 的描述符。例如:

Yes, you can use flock to do this. However, since you want to open the file with fopen instead of open, you'll need to first get the file descriptor using fileno. For example:

FILE* f = fopen(...);
int fd = fileno(f);
// flock should return zero on success
flock(fd, LOCK_EX);

这将放置一个排他锁-如果要共享锁,请更改 LOCK_EX LOCK_SH

That would place an exclusive lock - if you want a shared lock, change LOCK_EX to LOCK_SH.

这篇关于读取(打开)文件时如何阻止文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆