如何检查从.c文件读取的行是否包含#include <something>?

时间:2019-02-21 14:29:33

标签: c

我在执行任务时遇到问题。 我正在用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);
}

1 个答案:

答案 0 :(得分:1)

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

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

在进行此检查之前,您还需要剪切出'\ NEWLINE'。为了使您的处理与C一致,以便能够处理任何有效文件。

因此,您还需要跳过代码中#之前和之后的空格,并删除\\\n