lfsyue 发表于 2013-04-24 20:27

从文件中查找匹配字符串问题

废话不说,要求如标题:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#define MAXLINE 1024;

int linesNum;
static int sunday(const char* src, const char* des)
{
int len_s=strlen(src);
int len_d=strlen(des);
int next={0};
int i,j;
for(i=0;i<26;++i)
next=len_d+1;
for(j=0;j<len_d;++j)
next-'a']=len_d-j;
int pos=0;
while(pos<(len_s-len_d+1))
{
int i=pos;
int j;
for(j=0;j<len_d;++j,++i)
{
if(src!=des)
{
pos+=next-'a'];
break;
}
}
if(j==len_d)
return pos;
}
return-1;
}

int main(void)
{
FILE * fp;
char *line = NULL;
//char line;
size_t len = 0;
ssize_t read;
int end=0;

   fp = fopen("files", "r");
   while((fgets(line,1024,fp))!=NULL){   
linesNum++;
//end=strlen(line)-1;
//line=0;
printf("%d\n",linesNum);
puts(line);
if(sunday(line,"lianghui")>=0)
printf("find match line at:%d\n",linesNum);
      }   
   fclose(fp);   
}
运行出错:
Segmentation fault,求大神指导我该怎样做,先谢谢了

bzcat 发表于 2013-04-24 23:16

fopen返回值有检查吗?

txgc_wm 发表于 2013-04-25 22:55

本帖最后由 txgc_wm 于 2013-04-25 22:58 编辑

楼主,是否应该把你要实现的功能说的明白些。这么一坨没有排版过的代码,谁有那么好的心情看???#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>



#define LETTER_MAX_LEN 256
#define MAXLINE 1024

static int sunday(const char *src, const char *des)
{
        int i, pos = 0;
        int len_s, len_d;
        int alphabet = {0};

        if(src == NULL || des == NULL)
                return -1;

        len_s = strlen(src);
        len_d = strlen(des);

        for(i = 0; i < LETTER_MAX_LEN; i++)
                alphabet = len_d;

        for(i = 0; i < len_d; i++)
                alphabet] = len_d - i - 1;

        for(pos = 1; pos <= len_s - len_d; ) {
                for(i = pos - 1; i - pos + 1 < len_d; i++) {
                        if(src != des)
                                break;
                }
               
                if((i - pos + 1) == len_d)
                        return pos;
                else
                        pos += alphabet] + 1;
        }

        return -1;
}

int main(int argc, char **argv)
{
        FILE *fp = NULL;
        char line = {0};
        int linesNum;

        fp = fopen(argv, "r");
        if(fp == NULL) {
                printf("can not open file %s\n", argv);
                return -1;       
        }

        while ((fgets(line, MAXLINE, fp)) != NULL) {
                linesNum++;
                printf("%d\n", linesNum);
                puts(line);
                if (sunday(line, "lianghui") >= 0)
                        printf("find match line at:%d\n", linesNum);
        }

        fclose(fp);
        fp = NULL;

        return 0;
}

lfsyue 发表于 2013-04-29 21:53

问题已经解决,谢谢~
页: [1]
查看完整版本: 从文件中查找匹配字符串问题