2012-03-06 23 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