Introduction to ext2fs
The Extended File System (ext2) is a widely-used file system for Linux. It provides various APIs for file system manipulation and management which are encapsulated in the ext2fs library. In this post, we will explore some of the most useful APIs provided by ext2fs with practical code snippets.
API Examples
1. Initializing the File System
Before you can manipulate ext2 file system, you need to initialize the library.
#include
...
errcode_t result;
ext2_filsys fs;
result = ext2fs_open("/dev/sdXX", 0, 0, 0, unix_io_manager, &fs);
if (result) {
fprintf(stderr, "Failed to open filesystem");
return;
}
2. Reading the Superblock
struct ext2_super_block superblock;
result = ext2fs_read_sb(fs);
if (result) {
fprintf(stderr, "Failed to read superblock");
return;
}
superblock = *(fs->super);
3. Creating a New Inode
ext2_ino_t inode;
result = ext2fs_new_inode(fs, 2, 0, 0, &inode);
if (result) {
fprintf(stderr, "Failed to create new inode");
return;
}
4. Writing Data to Inode
char data[] = "Hello, ext2!";
blk_t block;
result = ext2fs_bmap2(fs, inode, 0, 0, data, &block);
if (result) {
fprintf(stderr, "Failed to write data to inode");
return;
}
5. Creating a Directory
result = ext2fs_mkdir(fs, "/newdir", 0777);
if (result) {
fprintf(stderr, "Failed to create directory");
return;
}
6. Listing Directory Contents
struct ext2_dir_entry *dir_entry;
ext2_ino_t dir_ino;
int offset = 0;
result = ext2fs_lookup(fs, EXT2_ROOT_INO, "dirname", strlen("dirname"), 0, &dir_ino);
if (result) {
fprintf(stderr, "Failed to find directory inode");
return;
}
while (true) {
result = ext2fs_get_dir_entry(fs, dir_ino, offset, NULL, &dir_entry);
if (result) {
break;
}
printf("Found entry: %s\n", dir_entry->name);
offset += dir_entry->rec_len;
}
App Example Using ext2fs APIs
#include
#include
int main() {
errcode_t result;
ext2_filsys fs;
result = ext2fs_open("/dev/sdXX", 0, 0, 0, unix_io_manager, &fs);
if (result) {
fprintf(stderr, "Failed to open filesystem");
return 1;
}
struct ext2_super_block superblock;
result = ext2fs_read_sb(fs);
if (result) {
fprintf(stderr, "Failed to read superblock");
return 2;
}
ext2_ino_t inode;
result = ext2fs_new_inode(fs, 2, 0, 0, &inode);
if (result) {
fprintf(stderr, "Failed to create new inode");
return 3;
}
printf("New inode created: %d\n", inode);
return 0;
}
This app opens an ext2 file system, reads the superblock, creates a new inode, and outputs the inode number.
Hash: e0c088e18d2bb256d76a87f7d3f836f05d51c178db06144dfccc72caa1150cce