【问题标题】:check if file is a c file and compile it检查文件是否为c文件并编译
【发布时间】:2019-05-10 19:18:35
【问题描述】:

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

【问题讨论】:

  • 检查文件扩展名应该没问题。然后在文件上运行system("gcc -c ")
  • OT:为了便于阅读和理解:始终缩进代码。在每个左大括号“{”后缩进。在每个右大括号 '}' 之前取消缩进。建议每个缩进级别为 4 个空格
  • 在调用gcc 时,始终启用警告。对于gcc,至少使用:-c -Wall -Wextra -Wconversion -pedantic -std=gnu11

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


【解决方案1】:

您的问题很可能被误导了(您可能有一个XY problem):编译C 很少是在其上运行编译器的小事:您可能需要知道-I 和@987654324 是什么@(和其他)需要编译的标志,需要链接的库等等。

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

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

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

如何让它运行我当前的文件?

类似这样的:

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);
}

【讨论】:

  • 所以可以说我的程序正在检查当前文件并且我想运行 system("gcc -c $file.c") 如何让它运行我当前的文件? system("gcc -c $ entry->d_name") 会起作用吗?
猜你喜欢
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2020-12-27
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
相关资源
最近更新 更多