#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#define FILE_PATH "/path/to/your/file.txt"
#define BUFFER_SIZE 1024
static int read_file(void) {
struct file *file;
char buffer[BUFFER_SIZE];
mm_segment_t oldfs;
int bytes_read = 0;
// Open the file
file = filp_open(FILE_PATH, O_RDONLY, 0);
if (IS_ERR(file)) {
printk(KERN_ERR "Failed to open file: %s\n", FILE_PATH);
return PTR_ERR(file);
}
// Read from the file
oldfs = get_fs();
set_fs(KERNEL_DS);
bytes_read = vfs_read(file, buffer, BUFFER_SIZE, &file->f_pos);
set_fs(oldfs);
if (bytes_read < 0) {
printk(KERN_ERR "Failed to read from file: %s\n", FILE_PATH);
filp_close(file, NULL);
return bytes_read;
}
// Close the file
filp_close(file, NULL);
// Print the read data
printk(KERN_INFO "Read %d bytes: %s\n", bytes_read, buffer);
return 0;
}
static int write_file(void) {
struct file *file;
char buffer[] = "Hello, world!";
mm_segment_t oldfs;
int bytes_written = 0;
// Open the file
file = filp_open(FILE_PATH, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (IS_ERR(file)) {
printk(KERN_ERR "Failed to open file: %s\n", FILE_PATH);
return PTR_ERR(file);
}
// Write to the file
oldfs = get_fs();
set_fs(KERNEL_DS);
bytes_written = vfs_write(file, buffer, strlen(buffer), &file->f_pos);
set_fs(oldfs);
if (bytes_written < 0) {
printk(KERN_ERR "Failed to write to file: %s\n", FILE_PATH);
filp_close(file, NULL);
return bytes_written;
}
// Close the file
filp_close(file, NULL);
printk(KERN_INFO "Wrote %d bytes to file: %s\n", bytes_written, FILE_PATH);
return 0;
}
static int __init file_io_init(void) {
printk(KERN_INFO "File IO module initialized\n");
read_file(); // Example: read from file during module initialization
write_file(); // Example: write to file during module initialization
return 0;
}
static void __exit file_io_exit(void) {
printk(KERN_INFO "File IO module exited\n");
}
module_init(file_io_init);
module_exit(file_io_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple Linux kernel module for file I/O operations");