2012-03-06 48 views
1

我想将目录转换为文件,我做了一些研究。在Linux中,inode结构存储有关文件和目录的元数据。我想将目录中的文件保护模式更改为文件,在C程序中使用inode结构将目录修改为文件

Print some general file info 

#include <time.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/stat.h> 
#include <sys/types.h> 

int main(int argc, char *argv[]) { 
struct stat file_stats; 

if(argc != 2) 
    fprintf(stderr, "Usage: fstat FILE...\n"), exit(EXIT_FAILURE); 

if((stat(argv[1], &file_stats)) == -1) { 
    perror("fstat"); 
    return 1; 
} 

printf("filename: %s\n", argv[1]); 
printf(" device: %lld\n",      file_stats.st_dev); 
printf(" inode: %ld\n",       file_stats.st_ino); 
printf(" protection: %o\n",      file_stats.st_mode); 
printf(" number of hard links: %d\n",   file_stats.st_nlink); 
printf(" user ID of owner: %d\n",    file_stats.st_uid); 
printf(" group ID of owner: %d\n",    file_stats.st_gid); 
printf(" device type (if inode device): %lld\n",file_stats.st_rdev); 
printf(" total size, in bytes: %ld\n",   file_stats.st_size); 
printf(" blocksize for filesystem I/O: %ld\n", file_stats.st_blksize); 
printf(" number of blocks allocated: %ld\n", file_stats.st_blocks); 
printf(" time of last access: %ld : %s",  file_stats.st_atime, ctime(&file_stats.st_atime)); 
printf(" time of last modification: %ld : %s", file_stats.st_mtime, ctime(&file_stats.st_mtime)); 
printf(" time of last change: %ld : %s",  file_stats.st_ctime, ctime(&file_stats.st_ctime)); 

return 0; 
} 

有什么方法可以将目录更改为文件?如何通过C程序修改inode结构?

+3

是不是有一个特别的理由不只是删除文件,然后创建一个目录? – Corbin 2012-03-06 07:09:33

+0

ya。我想通过处理文件来对目录进行一些操作。 – Nimit 2012-03-06 07:11:29

+0

目录已经是一个文件。你真的想做什么? – Duck 2012-03-06 07:33:43

回答

1

要打开任何文件,您必须使用开放系统调用。但目前开放的系统调用不允许任何人打开一个目录进行写入。如果您打开一个目录进行写入,它将返回错误(-1)并将errno设置为EISDIR。

还是要这样做,你必须重新实现Linux文件系统驱动程序的开放系统调用。

+0

有什么办法可以将目录转换成文件吗? – Nimit 2012-03-06 09:13:06

+2

我不认为有这样的选择。但您可以将内容复制到新文件,并可以用新创建的文件替换现有目录。 – theB 2012-03-06 10:04:54