实现linux cp 命令和修改配置文件
生活随笔
收集整理的這篇文章主要介紹了
实现linux cp 命令和修改配置文件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
cp指令用來代碼的拷貝
以下由文件編程代碼實現(xiàn)
代碼演示
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<stdio.h> #include <unistd.h> #include <string.h>#include <stdlib.h> int main(int argc,char**argv) {int fdSrc;int fdDes;char* readbuf=NULL;if(argc!=3){printf("parmar error");exit(-1);}fdSrc=open(argv[1],O_RDWR);int size=lseek(fdSrc,0,SEEK_END);readbuf=(char *)malloc(sizeof(char)*size+8);lseek(fdSrc,0,SEEK_SET);int n_readbuf=read(fdSrc,readbuf,size);fdDes=open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);//copy后argv[2]中的原本內(nèi)容會被覆蓋掉int n_write=write(fdDes,readbuf,strlen(readbuf));//write 返回寫入字節(jié)的長度close(fdSrc);close(fdDes);return 0; } // ./a.out demo14.c demo91.c ps:argc:表示輸入的三個參數(shù)argv:表示字符串數(shù)組argv[0]:表示 ./a.outargv[1]:表示 demo14.cargv[2]:表示 demo91.c其中文件都可以帶有自己路徑文件編程練習之配置文件的修改
代碼演示
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> int main(int argc,char**argv) {int fdSrc;char* readbuf=NULL;if(argc!=2){printf("parmar error");exit(-1);//文件退出}fdSrc=open(argv[1],O_RDWR);int size=lseek(fdSrc,0,SEEK_END);readbuf=(char *)malloc(sizeof(char)*size+8);lseek(fdSrc,0,SEEK_SET);int n_read=read(fdSrc,readbuf,size);char *p=strstr(readbuf,"LENG=");//在readbuf中查找字符串,如果找到返回L位置的指針if(p==NULL){printf("find fail\n");exit(-1);}p=p+strlen("LENG=");//指針向后移動到要修改的地方*p='5';//*p=5 可以將數(shù)字5寫入,但是會亂碼,并沒有出錯,只是我們看不懂lseek(fdSrc,0,SEEK_SET);int n_write=write(fdSrc,readbuf,strlen(readbuf));close(fdSrc);return 0; } // ./a.out file1 ps: file1是要修改的配置文件程序中寫入要修改的值 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的实现linux cp 命令和修改配置文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html:(33):文字排版粗体和斜体
- 下一篇: linux 写结构体到文件