① 如何用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'); } 这样, ...