① 如何用c語言實現linux裡面的tree指令
#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<string.h>
#defineMAXNAME200
voids_printf(char*filename,intdepth);
voids_dirwalk(char*dirname,intdepth,void(*fcn)(char*,int));
voidlistdirtree(char*dirname,intdepth);
intmain(intargc,char**argv)
{
if(argc==1)
listdirtree(".",0);
else
{
printf("%s ",argv[1]);
listdirtree(*++argv,0);
}
return0;
}
voidlistdirtree(char*dirname,intdepth)
{
structstatstbuf;
if((stat(dirname,&stbuf))==-1)
{
fprintf(stderr,"listdirtree:can'treadfile%sinformation! ",dirname);
return;
}
if((stbuf.st_mode&S_IFMT)==S_IFDIR)
s_dirwalk(dirname,depth,listdirtree);
}
voids_dirwalk(char*dirname,intdepth,void(*fcn)(char*,int))
{
charname[MAXNAME];
structdirent*fip;
DIR*dp;
if((dp=opendir(dirname))==NULL)
{
fprintf(stderr,"s_dirwalk:can'topen%s ",dirname);
return;
}
while((fip=readdir(dp))!=NULL)
{
if(strcmp(fip->d_name,".")==0||strcmp(fip->d_name,"..")==0)/*skipdirectory'.'and'..'*/
continue;
if(strlen(dirname)+strlen(fip->d_name)+2>sizeof(name))
{
fprintf(stderr,"s_dirwalk:%s/%sistoolong! ",dirname,fip->d_name);
return;
}
else
{
s_printf(fip->d_name,depth);
sprintf(name,"%s/%s",dirname,fip->d_name);
(*fcn)(name,depth+1);
}
}
closedir(dp);
}
voids_printf(char*filename,intdepth)
{
while(depth-->0)
printf("|");
printf("|--");
printf("%s ",filename);
}
② linux下如何用c語言調用shell命令
在c語言中調用shell命令的方法實現。
c程序調用shell腳本共有兩種方法
:system()、popen(),分別如下:
system()
不用自己去創建進程,系統已經封裝了這一步,直接加入自己的命令即可
popen()
也可以實現執行的命令,比system
開銷小
以下分別說明:
1)system(shell命令或shell腳本路徑);
system()
會調用fork()產生
子歷程,由子歷程來調用/bin/sh-c
string來履行
參數string字元串所代表的命令,此命令履行
完後隨即返回原調用的歷程。在調用system()期間sigchld
信號會被暫時擱置,sigint和sigquit
信號則會被漠視
。
返
回值:如果system()在調用/bin/sh時失敗則返回127,其他失敗原因返回-1。若參數string為空指針(null),則返回非零值。
如果
system()調用成功
則最後會返回履行
shell命令後的返回值,但是此返回值也有可能為system()調用/bin/sh失敗所返回的127,因
此最好能再反省
errno
來確認履行
成功
。
system命令以其簡略
高效的作用得到很很廣泛
的利用
,下面是一個例子
例:在/tmp/testdir/目錄下有shell腳本tsh.sh,內容為
#!/bin/sh
wget
$1
echo
"done!"
2)popen(char
*command,char
*type)
popen()
會調用fork()產生
子歷程,然後從子歷程中調用/bin/sh
-c來履行
參數command的指令。參數type可應用
「r」代表讀取,「w」代表寫入。遵循此type值,popen()會建立
管道連到子歷程的標准
輸出設備
或標准
輸入設備
,然後返回一個文件指針。隨後歷程便可利用
此文件指針來讀取子歷程的輸出設備
或是寫入到子歷程的標准
輸入設備
中。此外,所有應用
文
件指針(file*)操作的函數也都可以應用
,除了fclose()以外。
返回值:若成功
則返迴文件指針,否則返回null,差錯
原因存於errno中。注意:在編寫具suid/sgid許可權的程序時請盡量避免應用
popen(),popen()會繼承環境變數,通過環境變數可能會造成系統安全的問題。
例:c程序popentest.c內容如下:
#include
main
{
file
*
fp;
charbuffer[80];
fp=popen(「~/myprogram/test.sh」,」r」);
fgets(buffer,sizeof(buffer),fp);
printf(「%s」,buffer);
pclose(fp);
}
③ 怎麼用C語言實現linux的命令
命令是查詢當前登錄的每個用戶,它的輸出包括用戶名、終端類型、登錄日期及遠程主機,在Linux系統中輸入who命令輸出如下:
我們先man一下who,在幫助文檔里可以看到,who命令是讀取/var/run/utmp文件來得到以上信息的。
我們再man一下utmp,知道utmp這個文件,是二進制文件,裡面保存的是結構體數組,這些數組是struct utmp結構體的。
struct utmp {
short ut_type;
pid_t ut_pid;
char ut_line[UT_LINESIZE];
char ut_id[4];
char ut_user[UT_NAMESIZE];
char ut_host[UT_HOSTSIZE];
struct {
int32_t tv_sec;
int32_t tv_usec;
} ut_tv;
/***等等***/
};
要實現who只需要把utmp文件的所有結構體掃描過一遍,把需要的信息顯示出來就可以了,我們需要的信息有ut_user、ut_line、ut_tv、ut_host。
老師給的初始代碼:who1.c運行結果如下:
需要注意的是utmp中所保存的時間是以秒和微妙來計算的,所以我們需要把這個時間轉換為我們能看懂的時間,利用命令man -k time | grep 3搜索C語言中和時間相關的函數:
經過搜索發現了一個ctime()函數,似乎可以滿足我們的需求,於是對代碼中關於時間的printf進行修改:
printf("%s",ctime(&utbufp->ut_time));
編譯運行發現出來的結果雖然已經轉換成了我們能看懂的時間格式,但是很明顯這個時間是錯的:
搜索一下ut_time這個宏,發現它被定義為int32_t類型:
但是ctime()函數中要求參數的類型是time_t類型,所以重新定義一下類型,編譯運行之後,發現時間已經改成了正確的,但是發現()中的內容被換行了,猜想ctime()函數的返回值可能自動在最後補了一個字元\n:
一開始想通過\r\b來實現「退行」,但實踐後發現並不可取,最後考慮到直接修改字元串中最後一個字元為\0,讓其字元串結束,使輸出達到與系統who命令一樣的效果,即在輸出語句前添加如下代碼:
cp[strlen(cp)-1] = '\0'
最後編譯執行效果,發現解決了該問題:
雖然能看出基本上和who指令的執行結果一致,但是並非完全一樣,主要在兩點,第一是時間格式不一樣,第二個是比who執行的結果多了幾條,需要注意的是utmp中保存的用戶,不僅僅是已經登陸的用戶,還有系統的其他服務所需要的「用戶」,所以在顯出所有登陸用戶的時候,應該過濾掉其他用戶,只保留登陸用戶。我們可以通過ut_type來區別,登陸用戶的ut_type是USER_PROCESS。
先用if語句對執行結果進行過濾,效果如下:
接著解決時間格式問題,利用man命令收到了兩個非常有用的函數:localtime()和strftime(),localtime()是把從1970-1-1零點零分到當前時間系統所偏移的秒數時間轉換為本地時間,strftime()則是用來定義時間格式的,如:年-月-日,利用這兩個函數對時間進行修改後,結果顯示終於和系統中who命令一模一樣:
最終完整的代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#define SHOWHOST
void show_time(long timeval){
char format_time[40];
struct tm *cp;
cp = localtime(&timeval);
strftime(format_time,40,"%F %R",cp);
printf("%s",format_time);
}
int show_info( struct utmp *utbufp )
{
if(utbufp->ut_type == USER_PROCESS){
printf("%-8.8s", utbufp->ut_name);
printf(" ");
printf("%-8.8s", utbufp->ut_line);
printf(" ");
show_time(utbufp->ut_time);
printf(" ");
#ifdef SHOWHOST
printf("(%s)", utbufp->ut_host);
#endif
printf("\n");
}
return 0;
}
int main()
{
struct utmp current_record;
int utmpfd;
int reclen = sizeof(current_record);
if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){
perror( UTMP_FILE );
exit(1);
}
while ( read(utmpfd, ¤t_record, reclen) == reclen )
show_info(¤t_record);
close(utmpfd);
return 0;
}
④ 用C語言如何實現 linux下 grep 命令>
linux 應當是開放系統,也許可以找到源程序。
我曾寫過一個有部分 grep 功能 的程序grep_string.c,用於搜同一文件夾 文件內的字元串
若搜到,則顯示文件名,行號,行的內容。
程序如下:
/* ======================================================================*
* grep_string.c
* PC DOSprompt tool, partly similar to unix grep:
* grep string files
* where files is the file names used in DIR command
* open a temp file to store the file names in the file
* read each file name and open/grep/close it
* if match the string, print the line number and the line.
* -------------------------------------------------------------
* call ERASE/F grep_str_temp.tmp
* call DIR/B/A-D *
* L_o_o_n_i_e 2000-Nov
* ======================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Buff_size 40960
int DEBUG=0;
FILE *fin;
FILE *fout;
FILE *fname;
char namein[72], nameout[72], namelist[72];
char current_dir[72];
char current_file_name[72];
char target_string[64];
int L_dir; /* Length of current_dir\files string */
int L_target; /* Length of searched string */
int L_row; /* Length of the row fgets just got */
int L_filename; /* Length of current file name */
char *buff;
void init();
void message1(char * progname);
void search(char * target_string);
void clean_it(char * buff, int N_size);
main (int argc, char *argv[])
{
char command[200];
int I_file = 0;
if (argc < 3) (void) message1( argv[0] ); /* argc < 3, print usage and exit */
(void) init(); /* alloc buff */
strcpy(namelist,"C:\\temp\\grep_str_temp.tmp");
strcpy(current_dir, argv[2]);
strcpy(target_string, argv[1]);
L_target = strlen(target_string);
if (DEBUG == 1) {
printf("grep \"%s\" %s\n", target_string, current_dir);
printf("the length of target_string is: %d\n",L_target);
};
/* ------------------------------------------------------------*
* get name list and saved in grep_string_temp.tmp
* ------------------------------------------------------------*/
sprintf(command,"DIR/B/A-D %s > %s", current_dir, namelist);
system(command);
if ( (fname = fopen(namelist,"r") ) == NULL ) {
printf("\007Cann't open work file: %s ", namelist);exit(1);
};
while ( fgets( current_file_name, 72, fname) !=NULL ) {
strncpy(namein, current_file_name, strlen(current_file_name) - 1 );
if (DEBUG == 1) {
printf( "\007I will open %s and search \"%s\"\n", namein, target_string);
};
if ( (fin = fopen(namein,"r") ) == NULL ) {
printf("\007Cann't open current file: %s ", namein);
goto the_end_of_loop;
};
(void) search( target_string );
fclose(fin);
the_end_of_loop: ;
(void) clean_it( current_file_name, 72);
(void) clean_it( namein, 72);
}; /* end of main while loop */
fclose(fname);
if (DEBUG == 0 ) {
sprintf(command,"ERASE/F %s", namelist);
system(command);
};
exit(0);
} /* the End of main program */
/* =================================================================*
* init()
* init global
* L_o_o_n_i_e
* =================================================================*/
void init()
{
L_dir = 0;
L_target = 0;
L_row = 0;
L_filename;
buff = (char *) malloc( Buff_size * sizeof (char));
if (!buff) {
printf("\007No enough memory -- Can not alloc the Buff\n");
exit(2);
};
}
void message1 (char * progname)
{
fprintf(stderr, "========================================================\n");
fprintf(stderr, "The prog searchs a string in files\n");
fprintf(stderr, "If found the string then print the line on screen\n");
fprintf(stderr, "search a string in Chinese GB 8bit bytes is allowed\n");
fprintf(stderr, "\007Usage: %s targetstring files\n", progname);
fprintf(stderr, "For example: %s cgi-bin A*.html\n", progname);
fprintf(stderr, "For example: %s ÖDIÄ A*.html\n", progname);
fprintf(stderr, "Limit: maximum line width is %d bytes\n", Buff_size);
fprintf(stderr, "L_o_o_n_i_e 2000-Nov\n");
fprintf(stderr, "========================================================\n");
exit(1);
}
/* =====================================================================*
* search the target string
* L_target == target_string lenth
* LL == the line length
* if L_target >= LL skip the line
* otherwise loop:
i = 0 to LL - L_target
comp (buff[i],atrget_string,L_target)
if find, then output and goto next
* L_o_o_n_i_e
* ========================================================================*/
void search(char * target_string)
{
int i,j,NN;
int LL;
int ii;
int flag_print_name = 0;
NN = 0;
while ( fgets( buff, Buff_size, fin) !=NULL ) {
LL = 0;
LL = strlen(buff);
NN = NN + 1;
ii = LL - L_target;
if (ii < 0 ) goto Lab1;
for (i=0;i<ii;i++) {
if ( strncmp( &buff[i], target_string, L_target) == 0 ) {
if (flag_print_name == 0) {
printf("In %s\n",namein);
flag_print_name = 1;
};
printf("Line: %d: %s\n", NN, buff);
goto Lab1;
};
};
Lab1:;
(void) clean_it( buff, Buff_size);
};
if (DEBUG == 1) printf("%d lines, last row length=%d\n",NN,LL);
}
void clean_it(char * buff, int N_size)
{
int i;
for (i=0; i< N_size; i++) strncpy(&buff[i], "\0",1);
}
⑤ linux中cp命令如何用 C語言實現
1,首先需要了解cp的原理。
2,可以參考cp的源碼去了解其原理
3,cp命令的源碼可以在linux內核中找到。
4,或者下載busybox其中也會有cp的源碼
只有了解其原理之後才能談如何實現。參考代碼如下:
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<errno.h>
#include<unistd.h>
#include<string.h>
#defineBUF_SIZE1024
#definePATH_LEN128
voidmy_err(char*err_string,intline)
{
fprintf(stderr,"line:%d",line);
perror(err_string);
exit(1);
}
void_data(constintfrd,constintfwd)
{
intread_len=0,write_len=0;
unsignedcharbuf[BUF_SIZE],*p_buf;
while((read_len=read(frd,buf,BUF_SIZE))){
if(-1==read_len){
my_err("Readerror",__LINE__);
}
elseif(read_len>0){//把讀取部分寫入目標文件
p_buf=buf;
while((write_len=write(fwd,p_buf,read_len))){
if(write_len==read_len){
break;
}
elseif(write_len>0){//只寫入部分
p_buf+=write_len;
read_len-=write_len;
}
elseif(-1==write_len){
my_err("Writeerror",__LINE__);
}
}
if(-1==write_len)break;
}
}
}
intmain(intargc,char**argv)
{
intfrd,fwd;//讀寫文件描述符
intlen=0;
char*pSrc,*pDes;//分別指向源文件路徑和目標文件路徑
structstatsrc_st,des_st;
if(argc<3){
printf("用法./MyCp<源文件路徑><目標文件路徑> ");
my_err("argumentserror",__LINE__);
}
frd=open(argv[1],O_RDONLY);
if(frd==-1){
my_err("Cannotopnefile",__LINE__);
}
if(fstat(frd,&src_st)==-1){
my_err("staterror",__LINE__);
}
/*檢查源文件路徑是否是目錄*/
if(S_ISDIR(src_st.st_mode)){
my_err("略過目錄",__LINE__);
}
pDes=argv[2];
stat(argv[2],&des_st);
if(S_ISDIR(des_st.st_mode)){//目標路徑是目錄,則使用源文件的文件名
len=strlen(argv[1]);
pSrc=argv[1]+(len-1);//指向最後一個字元
/*先找出源文件的文件名*/
while(pSrc>=argv[1]&&*pSrc!='/'){
pSrc--;
}
pSrc++;//指向源文件名
len=strlen(argv[2]);
//.表示復制到當前工作目錄
if(1==len&&'.'==*(argv[2])){
len=0;//沒有申請空間,後面就不用釋放
pDes=pSrc;
}
else{//復制到某目錄下,使用源文件名
pDes=(char*)malloc(sizeof(char)*PATH_LEN);
if(NULL==pDes){
my_err("mallocerror",__LINE__);
}
strcpy(pDes,argv[2]);
if(*(pDes+(len-1))!='/'){//目錄缺少最後的'/',則補上』/『
strcat(pDes,"/");
}
strcat(pDes+len,pSrc);
}
}
/*打開目標文件,使許可權與源文件相同*/
fwd=open(pDes,O_WRONLY|O_CREAT|O_TRUNC,src_st.st_mode);
if(fwd==-1){
my_err("Cannotcreatfile",__LINE__);
}
_data(frd,fwd);
//puts("endof");
if(len>0&&pDes!=NULL)
free(pDes);
close(frd);
close(fwd);
return0;
}
⑥ 在Linux系統中,如何運行一個C語言程序
1、打開kali linux的終端。創建一個文件並命名為test.c。在終端輸入:touch test.c。
⑦ 如何用c語言實現 linux的rm命令
./rm filename和
在你的bash裡面輸入rm filename本質不是一樣的么
就是把那個rm的實現放在你的自己的mini bash裡面就可以了啊
調用
remove(filename);
就行了
⑧ c語言能使用linux命令嗎
c語言可以在linux下執行。
Linux下使用最廣泛的C/C++編譯器是GCC,大多數的Linux發行版本都默認安裝,不管是開發人員還是初學者,一般都將GCC作為Linux下首選的編譯工具。
GCC(GNU Compiler Collection,GNU編譯器集合),是一套由 GNU 開發的編程語言編譯器。
⑨ 如何用c語言實現echo linux
如Linux下的echo命令,是實現「參數回送」,Linux終端輸入#echohelloworld!helloworld!用C實現的代碼如下: /*echo.c*/main(intargc,char*argv[]){ while(--argc>0) printf("%s%c",*++argv,(argv>1)?'':'\n');} 也可以用如下代碼: /*echo.c*/ main(intargc,char*argv[]) {inti; for(i=1;i<argc;i++) printf("%s%c",argv,(i<argc-1)?'':'\n'); } 這樣, ...