溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

[Linux文件]使用lseek函數的偏移量來分次寫入用戶輸入的字符串的實例

發布時間:2020-09-19 09:17:57 來源:網絡 閱讀:582 作者:銀河星君 欄目:編程語言
 //這是一個使用lseek在一個文件中連續寫入用戶輸入字符串的應用
 //用戶輸入字符串由gets函數從鍵盤輸入獲取
 //這個地方必須用strlen函數而不是sizeof,前者是緩沖區實際大小而后者是緩沖區大小
 #include <fcntl.h>
 #include <stdio.h>
 #include <string.h>
 int main(int argc,char *argv[])
 {
   int temp,seektemp,i,j;
   int fd;                                    //文件描述符
   char writebuf[30];                 //用于存放待寫入數據,最長30字節
   char endbuf[] = "\r\n";            //用于存放回車換行
   if(argc!= 2)                               //如果參數錯誤
   {
   	 printf("Plz input the corrcet file name as './exam310lseekFun filename string'!\n");
   	 return 1;					//如果參數不正確則退出
   }
   fd = open(*(argv+1),O_RDWR|O_CREAT,S_IRWXU); //打開文件如果沒有則創建
   printf("Plz input the string and use Enter as the end!\n");  //提示輸入數據
   gets(writebuf);				//獲得字符串
   strcat(writebuf,endbuf);			//連接回車換行
   temp = write(fd,writebuf,strlen(writebuf));	//寫入數據
   seektemp = lseek(fd,0,SEEK_CUR);             //獲得當前的偏移量  
   for(i=0;i<10;i++)                            //連續寫入10個字符串
   {
     printf("%d,Plz input the string and use Enter as the end!\n",i);  //提示輸入數據
     gets(writebuf);                              //獲得字符串
     strcat(writebuf,endbuf);                     //連接回車換行    
     j = sizeof(writebuf) * (i+1);             //計算下一次的偏移量
     seektemp = lseek(fd,j,SEEK_SET);
     temp = write(fd,writebuf,strlen(writebuf));   //寫入數據
   }
   close(fd);                              //關閉文件
   return 0;
 }


向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女