【问题标题】:Searching a key word at a file c在文件 c 中搜索关键字
【发布时间】:2014-07-13 11:35:43
【问题描述】:

我一直在尝试创建一个在文件中搜索特定单词的函数...我的程序编译了,但它的执行在某个时候终止了... 功能是:

void search(struct word *w,FILE *f)
{
    char *c,*c2;
    int i,j,n,k,l;
    c=(char*)malloc(120*sizeof(char));
    c2=(char*)malloc(20*sizeof(char));
    while(f!=NULL)
    {                   
        j=0;
        i=1;
        fscanf (f,"%[^\n]%*c",c);
        printf("%s",c);
        n=strlen(c);
        k=0;
        l=j;
        while(l<=n && *(c+j)!=' ')
        {    
            *(c2+k)=*(c+j);
            printf("1");
            printf("%s",*(c2+k));
            printf("2");
            k=k+1;
            l=l+1;
        }      
        if(w->name==c2)
        {
            insert(i,j+1,name,&w);
        }
        else
        {
            if(l<n)
                j=l+1;
            k=0;
            c2=(char*)malloc(20*sizeof(char));
            l=j;
        }
        i=i+1;
        j=0;
    }
}

主要功能是:

   int main()
   {
       FILE *f;
       struct word *s;
       s=(struct word*)malloc(sizeof(struct word));

       struct word *hashtable[100];
       s->name=(char*)malloc(20*sizeof(char));
       scanf("%s",s->name);
       f=fopen("fileA.txt","rt");
       char *name="fileA.txt";
       search(s,f);
       printresults();
       system("pause");
       return(0);
   }

结构是:

struct position
{
   char *filename;
   int line;
   int place;
   struct position *next;
};

struct word
{
    char *name;
    struct word *right;
    struct word *left;
    struct position *result;
};

程序在printf("1")printf("2") 之间终止。

我的代码有什么问题?

【问题讨论】:

  • 两件事:Don't cast the result of mallocsizeof(char) 被指定为始终为 1。
  • "..它的执行会在某个时候终止.." 对于许多最终用户程序来说,这是完全正常的。
  • 好吧,@JoachimPileborg 你是对的......!我认为 %s 也会这样......!谢谢!
  • 但是,还是有问题……读完我的文件第一行后,程序又终止了……这次是什么问题?

标签: c file pointers


【解决方案1】:

如果崩溃发生在您打印"1""2" 之间某处,它应该很容易找到,因为那里只有一个语句。

而且它很容易找到

printf("%s",*(c2+k));

printf 函数被要求打印一个字符串,但您使用解引用运算符传递了一个 单个字符。当printf 将单个字符视为指向字符串的指针时,这会导致undefined behavior

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    相关资源
    最近更新 更多