Linux平台下利用系统接口函数按照行读写文件
2016-06-23 19:37
681 查看
要求:支持大文件(1M)一次性读入
源代码如下:
注意:运行此程序的时候,务必有文件"/root/wcy/test1/test.txt",如果没有这个目录下的这个文件,请修改成你的文件所在的目录。
源代码如下:
#include<stdio.h> #include<fcntl.h> #include<stdlib.h> #include<string.h> #define rwmode 2 //清屏命令函数 void clear() { char clscode[] = {0x1B, 0x5B, 0x48, 0x1B, 0x5B, 0x4A}; printf("%s",clscode); } //打开文件 int openFile() { int fd; fd=open("/root/wcy/test1/test.txt",rwmode); if(fd==-1){ printf("打开文件失败,文件路径不正确或者文件不存在!\n"); exit(0); }else return fd; } //读取文件 void readFile(int fd,char buffer[],int len){ int n=read(fd,buffer,len); buffer ='\0'; printf("文件的内容是:"); printf("%s",buffer); printf("\n"); } void lseekFile(int fd){ if(lseek(fd,0L,SEEK_END)==-1){ clear(); printf("定位读写文件失败!"); } else{ char block[512]=" lseek file"; write(fd,block,strlen(block)); printf("定位读写文件成功!\n"); } } int main(){ int fd,n,select; char buffer[1024*1024]; clear(); while(1){ printf("******************************\n") ; printf("****** 读写文件系统 ******\n"); printf("**** 1 显示特定文件内容:****\n"); printf("**** 2 定位读写文件内容:****\n"); printf("**** 0 退出本系统 *****\n"); printf("******************************\n"); printf("请输入功能编号:"); scanf("%d",&select); switch(select){ case 0: clear(); close(fd); exit(0); case 1: clear(); fd=openFile(); readFile(fd,buffer,sizeof(buffer)-1); close(fd); break; case 2: clear(); fd=openFile(); lseekFile(fd); close(fd); break; default: clear(); printf("你输入功能编号错误,请重新输入!\n"); } } exit(0); }
注意:运行此程序的时候,务必有文件"/root/wcy/test1/test.txt",如果没有这个目录下的这个文件,请修改成你的文件所在的目录。
相关文章推荐
- Centos下安装apahce的configure: error: APR not found. Please read the documentation解决办法
- 多台Linux服务器SSH相互访问无需密码
- Centos6.5安装Hadoop配置集群环境
- 阿里云windows service系统和linux系统上部署java工程
- Linux大数据处理踩坑实录
- libsvm的python接口在linux下的安装
- Linux新增磁盘、分区、格式化和自动挂载
- Linux系统备份与还原
- linux修改root用户的密码
- RHEL 8使用的内核版本
- 【原创】linux命令-Axel命令 - linux多线程下载 - 费元星 - 未来星开发团队
- centos 7.1 获取内核源码
- 初学CentOS的常见基本命令2
- 第12课第4.2节 字符设备驱动程序之中断方式的按键驱动_Linux中断处理结构
- 第12课第4.1节 字符设备驱动程序之中断方式的按键驱动_Linux异常处理结构
- 每日一linux命令(18)-------locate
- linux下安装Myeclipse提示Your system does not have sufficient memory to support MyEclipse
- CentOS下supervisor安装与使用
- 基于centos6构建私有gitbook平台
- Unix/Linux系统编程-知识脉络