首页 > 解决方案 > 如何检查我从 .c 文件中读取的行是否包含 #include?

问题描述

我在处理一项任务时遇到了问题。我正在用 C 进行不同的练习(我不能包含任何 c++ 库)。

我应该从 .c 文件中读取并输出 .o 文件中的所有内容,以及本规范。

“以 #include “filename.h” 开头的行应替换为名为 filename.h 的文件的全部内容。”

void writefile(int size, int *data, *file_path) {

    char outputFile[30];
    if (strcmp(file_name, "string_functions.c") == 0) {
        outputFile = "CW1_test_files/string_functions.o";
    }
    else outputFile = "CW1_test_files/math_functions.o";
    FILE *file;
    file = fopen(outputFile, "w");

    //In questo modo andiamo a verificare se e' opportuno ignorare o meno i commenti.
    int numberOfLines = 0;
    int numberOfComments = 0;

    if (file == NULL) {
        printf("Could not open file %s", filename);
        return -1;
    }
    else {
        char *line[1000];
        char *include = "#include";
        char *define = "#define";
        char ch;
        // file is equals to fp1
        while ((ch = fget(file)) != EOF){
            if ((strcmp(line[i], " ") != 0) && (strcmp(line[i], "\n") != 0) && (strcmp(line[i], "\t") != 0)) numberOfLines++;
            if (strcmp(line[i], "/") = 0) && (strcmp(line[i + 1], "/") numberOfComments++; //check the comments
            else if ((strcmp(line[i], "/") != 0) && (strcmp(line[i], " ") != 0)) continue;


        }

        printf(strcat("Number of Comments in the file %s: %d", file_path, numberOfComments));
        printf(strcat("Number of non-empty lines in the file %s: %d", file_path, numberOfLines));



    }



    fclose(file);

    //svolgere qui il resto del programma
    //stampare il file,, gestire gli #incl
    for (int i = 0; i < size; i++) {


    }
    writefile(size, data);
}

标签: c

解决方案


C 标准规定指令行具有这种形式。

<maybe spaces> # <maybe spaces> DIRECTIVE-NAME .....

在检查之前,您还需要剪掉“\NEWLINE”。为了使您的处理符合 C,以便能够处理任何有效文件。

因此,您还需要#在代码和 remve之前和之后跳过空格\\\n


推荐阅读