
linux寫檔案的方法:
1、使用fwrite函數
函數函數
用來讀寫一個資料塊。
一般呼叫形式
1 | fwrite(buffer,size, count ,fp);
|
登入後複製
說明
(1)buffer:是一個指針,對fread來說,它是讀入資料的存放位址。對fwrite來說,就是要輸出資料的位址。
(2)size:要讀寫的位元組數;
(3)count:要進行讀取和寫入多少個size位元組的資料項;
( 4)fp:檔案型指標
範例:
將目前時間寫入文字的程式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | int markfile(void )
{
FILE *sp ;
char count = 0;
char *currentime = NULL;
char *wday[] = { "Sun" , "Mon" , "Tue" , "Wed" , "Thu" , "Fri" , "Sat" };
time_t timep;
struct tm *p;
time(&timep);
p = localtime(&timep);
currentime = ctime(&timep);
printf( "%d/%d/%d" ,(1900+p->tm_year),(1+p->tm_mon),p->tm_mday);
printf( " %s %d:%d:%d\n" ,wday[p->tm_wday],p->tm_hour,p->tm_min,p->tm_sec);
if ((sp = fopen ( "/root/kay/mark.txt" , "a+" )) == NULL)
return 0;
fwrite(currentime,size(currentime)-1,1,sp);
fclose(sp);
return 1;
}
|
登入後複製
2、使用echo指令
該指令格式如下:
1 | [root@localhost ~]# echo [选项] [输出内容]
|
登入後複製
選項:
-e:支援反斜線控制的字元轉換(具體請參閱表1)
-n:取消輸出後行末的換行符號(內容輸出後不換行)
#範例:
1 2 | echo 'i love u' >a.txt *在a.txt这个文件中输入i love u,如果没有这个文件则创建。如果有这个文件,那么
新内容代替原来的内容。
|
登入後複製
推薦學習:linux教學
#
以上是linux怎麼寫文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!