简体   繁体   English

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

[英]How can I check if the line that i read from a .c file contains #include<something>?

I got an issue working on a task. 我在执行任务时遇到问题。 I am making different exercises in C (I can't include any c++ libraries). 我正在用C做不同的练习(我不能包含任何c ++库)。

I should read from a .c file and output everything in a .o file solving as well this specification. 我应该从.c文件中读取内容,并在解决该规范的.o文件中输出所有内容。

"A line that begins with #include “filename.h” should be replaced with the entire contents of the file called filename.h." “以#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);
}

The C standard specifies that a directive line has this form. C标准指定指令行具有这种形式。

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

Before to check for this, you also need to cut out the '\\NEWLINE'. 在进行此检查之前,您还需要剪裁'\\ NEWLINE'。 In order for your processing to be conforming with C, so to be able to process any valid file. 为了使您的处理与C一致,以便能够处理任何有效文件。

So you also need to skip the spaces before and after the # in your code and remve \\\\\\n . 因此,您还需要跳过代码中#之前和之后的空格,并删除\\\\\\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM