[Linux文件]將用戶輸入的字符串寫入文件實例
阿新 • • 發佈:2017-11-18
linux文件 字符串
//使用gets函數從標準輸入(鍵盤)獲得一個以回車換行為結束的字符串,可以帶空格 //運行時候屏幕會提示輸入字符處,以回車結尾 //需要註意的是待輸入的字符串存放在writebuf中,不能超過30字節並且不會帶回車換行 #include <fcntl.h> #include <stdio.h> #include <string.h> int main(int argc,char *argv[]) { int fd; //文件描述符 int temp; //臨時變量 char writebuf[30]; //用於存放寫入字符串 if(argc != 2) //如果參考字符串錯誤 { printf("Plz input the correct file name as ‘exam307WriteFun filename‘\n"); //輸出提示字符串 return 1; } else { fd = open(*(argv + 1),O_RDWR|O_CREAT,S_IRWXU); //打開文件,如果沒有則創建 } printf("The File Descriptor is %d\n",fd); //打印文件描述符 printf("Plz input the strings and use Enter as the end!\n"); gets(writebuf); //將終端輸入的數據寫入文件 temp = write(fd,writebuf,strlen(writebuf)); //使用文件描述符調用文件 printf("The input length is %d\n",temp); close(fd); return 0; }
本文出自 “10628473” 博客,請務必保留此出處http://10638473.blog.51cto.com/10628473/1983008
[Linux文件]將用戶輸入的字符串寫入文件實例