<Linux> Linux Driver文件读取

本文提供了一个在Linux环境下使用C语言实现的文件读取示例。通过此示例,读者可以了解到如何打开一个文件、读取文件内容,并正确关闭文件。此外,还展示了如何处理读取过程中可能出现的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

void driver_read_file(const char *filename)
{
	struct file *pfile;
	mm_segment_t old_fs;
	char read_buf[100] = {0};
	struct inode *inode;
	int ret;
	off_t fsize;
	int pkg_size = 64;
	int left;
	int read_size;

	pfile = filp_open(filename, O_RDONLY, 0);

	if (IS_ERR(pfile)) {
		pr_err("Open %s failed!\n", filename);
		return;
	}
	old_fs = get_fs();
	set_fs(KERNEL_DS);

	inode = pfile->f_dentry->d_inode;
	fsize = inode->i_size;

	pr_err("file size: %ld bytes\n", fsize);
	pr_err("file content: \n");
	left = fsize;
	while (left > 0) {
		if (left > pkg_size) {
			read_size = pkg_size;
		}
		else {
			read_size = left;
		}
		ret = pfile->f_op->read(pfile, read_buf, read_size, &pfile->f_pos);
		if (ret < 0) {
			pr_err("read data failed, ret: %d\n", ret);

			filp_close(pfile, NULL);
			set_fs(old_fs);
			return;
		}
		pr_err("%s\n", read_buf);
		left -= read_size;
	}
	filp_close(pfile, NULL);
	set_fs(old_fs);
}

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>SQLite 数据显示(替代方案)</title> </head> <body> <h1>SQLite 数据显示</h1> <table border="1"> <tr> <th>ID</th> <th>Name</th> </tr> <% Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { // 加载 SQLite 驱动 Class.forName("org.sqlite.JDBC"); // 连接到 SQLite 数据库 conn = DriverManager.getConnection("jdbc:sqlite:C:/Users/LENOVO/Documents/代码文件/ceshi.db"); // 准备 SQL 查询语句 String sql = "SELECT id, name FROM ceshi_table"; pstmt = conn.prepareStatement(sql); // 执行查询 rs = pstmt.executeQuery(); if (rs.next()) { do { int id = rs.getInt("id"); String name = rs.getString("name"); %> <tr> <td><%= id %></td> <td><%= name %></td> </tr> <% } while (rs.next()); } else { out.println("<tr><td colspan='2'>未找到数据</td></tr>"); } } catch (ClassNotFoundException e) { out.println("<tr><td colspan='2'>驱动加载失败:" + e.getMessage() + "</td></tr>"); } catch (SQLException e) { out.println("<tr><td colspan='2'>SQL 执行错误:" + e.getMessage() + "</td></tr>"); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { out.println("<tr><td colspan='2'>资源关闭错误:" + e.getMessage() + "</td></tr>"); } } %> </table> </body> </html> 显示不出来数据
04-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值