分享

数据结构与算法分析(C)1.4

 雪漫渝州 2017-06-30

问题描述:编写一个程序,使它读入被include语句修饰的一个文件并且输出这个文件。

分析:这道题的思路很简单,首先,读入源文件,然后在源文件中查找#include,然后获取包含的文件名,然后fread到内存中,如此继续下去。
有个问题纠结了很久:当在查找过程中发现strcpy(include,”#include”);时也会出现”#include”字符,应该对它进行过滤。

//include zuhonglei
//
#include <stdio.h>
#include <string.h>

int main(int argc,char *argv[]){
    if(argc<1)
        return -1;
    char *name = argv[0];
    char fullName[20];
    strcpy(fullName,name);
    strcpy(fullName+strlen(name),".c");
    printf("%s\n",fullName);

    FILE *fp = fopen(fullName,"r+");
    if(!fp)
        return -1;
    char context[4097];
    char context2[4097];
    context2[4096] = '\0';
    context[4096] = '\0';

    while(fread(context,sizeof(char),4096,fp)!=0){
        printf("%s\n",context);
    }
    fclose(fp);
    //check the name of include 
    int i,j,index;

    char include[10];
    strcpy(include,"#include");
    index = 0;
    int nameIndex = 0;

    char fileName[40];
    char *prefix = "/usr/include/";
    strcpy(fileName,prefix);
    int fileLen = strlen(fileName);

    for(i = 0;i<4097;i++){  
        if(context[i]=='/'&&context[i+1]=='/')//delete the whole line //
        {
            for(j = i;context[j]!='\n';j++);
            i = j;
            continue;
        }
        if(include[index]!='\0'){
            if(context[i]!=include[index]){
                index = 0;
            }
            else
                index++;
        }
        if(include[index]=='\0'){
            int tmp = fileLen;
            if(context[i+1]!=' '){
            index=0;    
            continue;
            }   
            while(1){
                i++;
                if(context[i]=='>'){
                    index = 0;
                    break;
                }
                if((context[i]>='a'&&context[i]<='z')||context[i]=='.')
                    fileName[tmp++] = context[i];
            }
            fileName[tmp] = '\0';//delete >

            printf("read fileName:%s\n",fileName);
            fp = fopen(fileName,"r+");
            if(!fp)
                return -1;
            while(fread(context2,sizeof(char),4096,fp)!=0)
                printf("%s\n",context2);
            fclose(fp);

        }
    }
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约