Linux 读取文件n行并删除方法
生活随笔
收集整理的這篇文章主要介紹了
Linux 读取文件n行并删除方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近工作中讀取對AC或者AP產生的Event的文件并發送ACS后刪除已發送的內容,下次發送未發送event。產生的event存入event文件中,要對event.dat文件進行文件操作,以下是操作流程!
void ParseEvent(void) {FILE *fp,*dfp;char cp[1024],dir[128],ddir[128];struct stat buf;memset(dir,0,sizeof(dir));memset(ddir,0,sizeof(ddir));sprintf(dir,"event.dat");sprintf(ddir,"event.dat.bak");if(!access(dir,F_OK)){fp = fopen(dir,"r+");dfp = fopen(ddir,"w+");if(fp && dfp){while (fgets (cp, sizeof(cp), fp) != NULL){// remove the line start with '#', ' ', '\n', '\0'if ( cp[0] == '#' || cp[0] == ' ' || cp[0] == '\n' || cp[0] == '\0' ){continue;}// read NUM_LINES lines from the fileif( ++ec < NUM_LINES){ FireEvent(cp);}else{fprintf(dfp,"%s\n",cp);}}fclose(fp);fclose(dfp);// sync all the buffer or cache to the file systemsync();// rename() if the file exist, the file will be replaced.rename(ddir,dir);}} }
總結
以上是生活随笔為你收集整理的Linux 读取文件n行并删除方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vim skills
- 下一篇: oracle sqlplus执行脚本_连