检查文件是否为c文件并进行编译

时间:2018-12-09 20:28:39

标签: c file compilation operating-system system-calls

我想在目录及其文件和子目录上递归运行。假设该目录可以包含file(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文件?以及如何使用代码进行编译? 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您的问题很可能被误导了(您可能有一个XY problem):编译C很少是在其上运行编译器的琐碎事情:您可能需要知道{{ 1}}和-I(和其他)标志需要与之一起编译,需要链接哪些库等,等等。

  

如何检查文件是否为c文件?以及如何使用代码进行编译?

您可以运行-D,如果它编译(system("gcc -c $file.c")返回0),则可能是一个system文件。

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

>
  

如何使其运行我的当前文件?

类似这样的东西:

C