检查文件是否是c文件并编译它

check if file is a c file and compile it

我想 运行 递归地遍历目录及其文件和子目录。假设该目录可以包含任何文件之王(c,txt,python...) 检查当前文件是否为 c 文件并编译它如果是。 这是我目前所拥有的:

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdlib.h>
#include<errno.h> 

void listdir(const char *name, int indent)
 {
  DIR *dir;
   struct dirent *entry;

if (!(dir = opendir(name)))
    return;

while ((entry = readdir(dir)) != NULL) {
    if (entry->d_type == DT_DIR) {
        char path[1024];
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue;
        snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
        printf("%*s[%s]\n", indent, "", entry->d_name);
        listdir(path, indent + 2);
    } else {
        printf("%*s- %s\n", indent, "", entry->d_name);
    }
}
closedir(dir);
}

int main(void) {
listdir(".", 0);
return 0;
}

如何检查文件是否为c文件?以及如何使用代码编译它? 任何帮助将不胜感激。

你的问题很可能被误导了(你可能有一个 XY problem):编译 C 很少是 运行 对它进行编译的微不足道的事情:你会可能需要知道编译时需要使用哪些 -I-D(以及其他)标志,需要链接哪些库,等等

how can I check if a file is a c file? and how to I compile it using the code?

你可以 运行 system("gcc -c $file.c") 如果它编译 (system returns 0),它可能是一个 C 文件。

注意:如果文件 没有 编译,可能是因为它不是 C 文件,或者因为您没有将正确的标志传递给编译器。

how do I make it run my current file?

像这样:

char path[PATH_MAX];
char cmd[4096 + 2*PATH_MAX];

snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); 
snprintf(cmd, sizeof(cmd), "gcc -c %s -o %s.o", path, path);
if (system(cmd) == 0) {
  printf("Compiled %s to %s.o\n", path, path);
}