日期:2014-05-16  浏览次数:20766 次

linux/mac 如何通过c函数禁止用户重命名 ?
是这样的,我开始的时候制定一个文件名,例如:test.txt

然后fopen("test.txt","w"),fwrite

写了一段时间之后,我要读取这个文件,而在这之前文件名被修改成fuck.txt了,这样我就找不到我的文件了,请问该如何禁止用户更改正在写入/读取的文件名 ?

流程是:
fpwrite = fopen("test.txt","w");
fwrite() ...
//在 fopen("test.txt","r");之前,文件名被更改了。
fpread = fopen("test.txt","r");
fread()...
fclose(fpread);
fwrite() ...
fclose(fpwrite);


windows下是无法修改正在读写的文件名的,不知道linux下为什么要这样设计。
------解决方案--------------------
使用fcntl来控制文件吧
------解决方案--------------------
应该可以用文件锁
看看这个能否帮助你
http://blog.chinaunix.net/uid-20498361-id-1940273.html
------解决方案--------------------
前排学习一下,顺便提供一些资料。
1.  维基百科 file locking
2. 最近在读现代操作系统的时候,发现书中讲到*nix操作系统中的link的工作原理时,稍微提到了一些知识:
Understanding how link works will probably make it clearer what it does. Every file in UNIX has a unique number, its i-number, that identifies it. This inumber is an index into a table of  i-nodes,  one per file, telling who owns the file, 
where its disk blocks are, and so on. A directory is simply a file containing a set of (i-number, ASCII name) pairs. In the first versions of UNIX, each directory entry was 16 bytes-2 bytes for the i-number and 14 bytes for the name. Now a 
more complicated structure is needed to support long file names, but conceptually a directory is still a set of (i-number, ASCII name) pairs. In Fig. 1-21,  mail  has inumber 16, and so on. What link does is simply create a new directory entry with a (possibly new) name, using the i-number of an existing file. In Fig. 1-21(b), two entries have the same i-number (70) and thus refer to the same file. If either one is later removed, using the unlink system call, the other one remains. If both are removed, UNIX 00sees that no entries to the file exist (a field in the i-node keeps track of the number of directory entries pointing to the file), so the file is removed from the disk. 
3. http://unix.stackexchange.com/questions/93399/how-to-prevent-users-from-renaming-files-while-providing-write-permissions-on-li
这里提到:
To rename a file, write permissions to the file don't matter, renaming a file is a change to the directory, not the file. That's changing the directory entry to have a different name pointing to the file.
------解决方案--------------------
我对第二段的理解:
在类unix上,一个文件对应一个底层数据结构inode。这些inode构成一张表,而我们所谓的文件只是这个文件对应的inode在这个表中的索引值——不妨以i-number来表示。

而linux上的目录/文件夹,只是一个特殊的文件(li