<Linux> Linux Driver文件读取

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

任务描述 本关任务:根据编程要求,完成任务。 编程要求 编写独立应用程序,读取 Linux 系统本地文件 /data/bigfiles/test.txt,然后统计出文件的行数;通过 maven 工具将整个应用程序编译打包成 JAR 包,并将生成的 JAR 包通过 spark-submit 提交到 Spark 中运行,将运行结果保存到 /root/maven_result.txt 文件中。 示例 pom.xml 文件如下: <project> <groupId>cn.edu.xmu</groupId> <artifactId>simple-project</artifactId> <modelVersion>4.0.0</modelVersion> <name>Simple Project</name> <packaging>jar</packaging> <version>1.0</version> <repositories> <repository> <id>jboss</id> <name>JBoss Repository</name> <url>http://repository.jboss.com/maven2/</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-core_2.11</artifactId> <version>2.1.0</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/scala</sourceDirectory> <plugins> <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <executions> <execution> <goals> <goal>compile</goal> </goals> </execution> </executions> <configuration> <scalaVersion>2.11.8</scalaVersion> <args> <arg>-target:jvm-1.5</arg> </args> </configuration> </plugin> </plugins> </build> </project> 测试说明 平台将对你编写的代码进行评测,如果与预期结果一致,则通关,否则测试失败。 开始你的任务吧,祝你成功!
最新发布
11-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值