歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> linu學習筆記(四):write,read函數

linu學習筆記(四):write,read函數

日期:2017/3/3 12:17:58   编辑:Linux技術

先上一段代碼:

#include<string.h>
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<error.h>
#include<stdlib.h>
/*自定義的錯誤處理函數*/
void my_err(const char *err_string,int line)
{
    fprintf(stderr,"line:%d ",line);//stderr 輸出到標准顯示設備
    perror(err_string);             //打印錯誤信息
    exit(1);
}
/*自定義的讀數據函數*/
int my_read(int fd)
{
    int len;
    int ret;
    int i;
    char read_buf[64];                           //定義一個字符數組用來當做緩沖
   /*獲取文件長度並保持文件讀寫指針在文件開始處*/
    if(lseek(fd,0,SEEK_END)==-1){                //移動到文件尾部
	my_err("lseek",__LINE__);
    }
    if((len=lseek(fd,0,SEEK_CUR))==-1) {         //獲取文件當前的偏移相對於文件開頭
        my_err("lseek",__LINE__);
    }
    if((lseek(fd,0,SEEK_SET))==-1) {             //移動到文件開頭
        my_err("read",__LINE__);
    }
    printf("len:%d\n",len);
    /*讀數據*/
    if((ret=read(fd,read_buf,len))==-1){
	my_err("read",__LINE__);
    }
    /*打印數據*/ 
    for(i=0;i<len;i++){
	printf("%c",read_buf[i]);
    }
    printf("\n");
    return ret;
}

int main()
{
    int fd;
    char write_buf[32] ="hellow world";
    /*在當前目錄下創建文件example_63.c*/
    //if((fd=creat("example_63.c",S_IRWXU))==-1){                             
    if((fd=open("example_63.c",O_RDWR|O_CREAT|O_TRUNC,S_IRWXU))==-1){    //創建一個可讀寫的文件 如果這個文件存在則把內容清空 清空的參數是
	my_err("open",__LINE__);                                         //O_TRUNC ,S__IRWXU是設置用戶操作文件的權限。
    }else{
        printf("creat file success\n");
    }
    /*寫數據*/
    if(write(fd,write_buf,strlen(write_buf))!=strlen(write_buf)){    //如果寫入數據不等於原來數據的長度則打印錯誤信息
        my_err("write",__LINE__);
    }
    my_read(fd);                                                       //調用讀取函數讀取數據這個行應該是刪除多打了一行
    /*演示文稿*/
    printf("/*-------------------------*/\n");
    if(lseek(fd,10,SEEK_END)==-1){
	my_err("write",__LINE__);
    }
    my_read(fd);
    close(fd);
    return 0;
}
兩個子函數一個用來處理錯誤主要調用perror()這個函數,這個函數之前筆記應該學過英文解說:The perror() function produces a message on standard error describing the last error encountered during a call to a system or library function.主要用於對上次調用系統或者庫函數出錯時的錯誤描述首先先打印括號中的字符然後才是錯誤的內容。第二個子函數是用來讀數據的,其中有個__LINE__參數是用來打印當前行號的,當運行出錯時會很方便的顯示出當前錯誤代碼的行號。關於代碼的解釋放在代碼注釋中

Copyright © Linux教程網 All Rights Reserved