|
发表于 2008-6-5 13:27:33
|
显示全部楼层
帮你写好了,还有问题么?
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc, char *argv[])
{
DIR *dp;
pid_t pid;
int status=0;
struct dirent *dirp;
char name[100][100];
char buf[80];
int i=0;
int file_num, result;
char* cmd_argv[] = {"gcc","-o","exec_file","source_file",(char *)0};
const char exec_file_type[] = ".out";
if (NULL == (dp=opendir(argv[1])))
{
fprintf(stderr, "Can' open %s directiory\n",argv[1], strerror(errno));
exit(-1);
}
while ( NULL != (dirp = readdir(dp)))
{
const char *p = dirp->d_name;
for (; *p && *p != '.'; ++p);
if (0 == strcmp(p, ".c"))
{
//printf("File name: %s\n", dirp->d_name);
strcpy(name[i++], dirp->d_name);
}
}
file_num = i;
closedir(dp);
// enter into working directory
chdir(argv[1]);
getcwd(buf, sizeof(buf));
printf("Current working directory is %s\n", buf);
printf("total %d source files\n\n", file_num);
// Begin to work
for (i=0; i<file_num; i++)
{
printf("start compile %s\n", name);
// set output filename
int len = strlen(name) + sizeof(exec_file_type) + 1;
char* temp = malloc( len * sizeof(char));
strcpy(temp, name);
cmd_argv[2] = strcat(temp, exec_file_type);
// set input filename
cmd_argv[3] = name;
pid = fork();
if (pid < 0)
{
printf("fork failed, try again\n");
exit(1);
} else if (pid == 0)
{
// This is child process
//printf("This is child process : %d\n", getpid());
if ( (result=execv("/usr/bin/gcc", cmd_argv)) == -1 )
{
printf("compile %s failed\n", name);
printf("error: %d\n", errno);
}
} else {
// This is parent process, wait for child process finish.
pid = wait(&status);
//printf("child's pid = %d\texit status=%d\n",pid,status);
printf("finish compile %s\n\n", name);
if(temp != NULL) free(temp);
}
}
return 0;
}
结果
e390977@ch71DT4nwhz1x /home/ray/c++/make
$gcc -o my_make my_make.c
e390977@ch71DT4nwhz1x /home/ray/c++/make
$./my_make.exe test/
Current working directory is /home/ray/c++/make/test
total 2 source files
start compile calnumber.c
finish compile calnumber.c
start compile my_make.c
finish compile my_make.c
e390977@ch71DT4nwhz1x /home/ray/c++/make
$ll test/
total 28K
-rw-r--r-- 1 e390977 ???????? 291 May 26 13:58 calnumber.c
-rwxr-xr-x 1 e390977 mkgroup-l-d 9.2K Jun 5 13:16 calnumber.c.out*
-rw-r--r-- 1 e390977 mkgroup-l-d 2.6K Jun 5 13:10 my_make.c
-rwxr-xr-x 1 e390977 mkgroup-l-d 14K Jun 5 13:16 my_make.c.out*
e390977@ch71DT4nwhz1x /home/ray/c++/make
$file test/*
test/calnumber.c: ASCII C program text
test/calnumber.c.out: MS-DOS executable PE for MS Windows (console) Intel 80386 32-bit
test/my_make.c: ASCII C program text, with CRLF line terminators
test/my_make.c.out: MS-DOS executable PE for MS Windows (console) Intel 80386 32-bit
头一次贴代码,居然不能缩进。到我的博客上看吧http://raychen1984.cublog.cn/ |
|