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