zoukankan      html  css  js  c++  java
  • Linux平台下利用系统接口函数按照行读写文件

    要求:支持大文件(1M)一次性读入

    源代码如下:

    #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("打开文件失败,文件路径不正确或者文件不存在!
    ");
           exit(0);
       }else return fd;
     
    }
    
    //读取文件
    void readFile(int fd,char buffer[],int len){
    
       int n=read(fd,buffer,len);
       buffer[n]='';
       printf("文件的内容是:");
       printf("%s",buffer);
       printf("
    ");
    }
    
    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("定位读写文件成功!
    ");
       }
    
    }
    
    int main(){
     
      int fd,n,select;
      char buffer[1024*1024];
      clear();
      while(1){
      printf("******************************
    ") ; 
      printf("******   读写文件系统   ******
    ");
      printf("****  1 显示特定文件内容:****
    ");
      printf("****  2 定位读写文件内容:****
    ");
      printf("****  0 退出本系统       *****
    ");
      printf("******************************
    ");
      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("你输入功能编号错误,请重新输入!
    ");
      }
     }
      exit(0);
    }
    

    注意:运行此程序的时候,务必有文件"/root/wcy/test1/test.txt",如果没有这个目录下的这个文件,请修改成你的文件所在的目录。

  • 相关阅读:
    慎用const_cast
    python中string的操作函数
    C++ Const总结
    python dict sorted 排序
    "没有找到MSVCP80D.dll,因此这个应用程序未能启动。重新安装应用程序...
    提高你开发效率的十五个 Visual Studio 使用技巧
    一些 python 插件 编译安装的注意事项
    html 制作表格 合并 样式
    将一个表的数据更新到另一个表中
    屏蔽web页面的右键,但不屏蔽输入框中的右键
  • 原文地址:https://www.cnblogs.com/wangchaoyuan/p/5612011.html
Copyright © 2011-2022 走看看