Linux 创建文件的应用和驱动代码
时间: 2023-05-25 08:01:40 浏览: 119
A:
Linux创建文件的应用代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char str[] = "This is a file created by Linux.";
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
return 0;
}
```
该程序会在当前路径下创建一个名为“file.txt”的文件,并向其中写入字符串“This is a file created by Linux.”
Linux创建文件的驱动代码:
```c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
MODULE_LICENSE("GPL");
static int my_open(struct inode *inode, struct file *file)
{
printk(KERN_INFO "mychardevice : open()\n");
return 0;
}
static ssize_t my_read(struct file *file, char *buf, size_t count, loff_t *pos)
{
printk(KERN_INFO "mychardevice : read()\n");
return 0;
}
static ssize_t my_write(struct file *file, const char *buf, size_t count, loff_t *pos)
{
printk(KERN_INFO "mychardevice : write()\n");
return 0;
}
static int my_close(struct inode *inode, struct file *file)
{
printk(KERN_INFO "mychardevice : release()\n");
return 0;
}
static struct file_operations my_fops =
{
.owner = THIS_MODULE,
.open = my_open,
.release = my_close,
.read = my_read,
.write = my_write,
};
static int __init mychardevice_init(void)
{
printk(KERN_INFO "mychardevice : init()\n");
register_chrdev(0, "mychardevice", &my_fops);
return 0;
}
static void __exit mychardevice_exit(void)
{
printk(KERN_INFO "mychardevice : exit()\n");
unregister_chrdev(0, "mychardevice");
}
module_init(mychardevice_init);
module_exit(mychardevice_exit);
```
该驱动代码会注册一个名为“mychardevice”的字符设备,并提供设备文件的打开、读、写、关闭等接口。通过系统调用可以使用这些接口来创建文件或向文件中写入数据。
阅读全文