内核中读写文件的方法

 1 static int android_readwrite_file(const A_CHAR *filename, A_CHAR *rbuf, const A_CHAR *wbuf, size_t length)
 2 {
 3     int ret = 0;
 4     struct file *filp = (struct file *)-ENOENT;
 5     mm_segment_t oldfs;
 6     oldfs = get_fs();
 7     set_fs(KERNEL_DS);
 8     do {
 9         int mode = (wbuf) ? O_RDWR : O_RDONLY;
10         filp = filp_open(filename, mode, S_IRUSR);
11         if (IS_ERR(filp) || !filp->f_op) {
12             AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("%s: file %s filp_open error\n", __FUNCTION__, filename));
13             ret = -ENOENT;
14             break;
15         }
16     
17         if (length==0) {
18             /* Read the length of the file only */
19             struct inode    *inode;
20 
21             inode = GET_INODE_FROM_FILEP(filp);
22             if (!inode) {
23                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("%s: Get inode from %s failed\n", __FUNCTION__, filename));
24                 ret = -ENOENT;
25                 break;
26             }
27             ret = i_size_read(inode->i_mapping->host);
28             break;
29         }
30 
31         if (wbuf) {
32             if ( (ret=filp->f_op->write(filp, wbuf, length, &filp->f_pos)) < 0) {
33                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("%s: Write %u bytes to file %s error %d\n", __FUNCTION__, 
34                                 length, filename, ret));
35                 break;
36             }
37         } else {
38             if ( (ret=filp->f_op->read(filp, rbuf, length, &filp->f_pos)) < 0) {
39                 AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("%s: Read %u bytes from file %s error %d\n", __FUNCTION__,
40                                 length, filename, ret));
41                 break;
42             }
43         }
44     } while (0);
45 
46     if (!IS_ERR(filp)) {
47         filp_close(filp, NULL);
48     }
49     set_fs(oldfs);
50 
51     return ret;
52 }
这段代码是从wifi 驱动中copy出来的。可作为分析参考。还有一个可参考的代码是 usb_massstorage.c

转载于:https://www.cnblogs.com/soc-linux-driver/archive/2012/08/15/2639595.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值