繁体   English   中英

尝试模拟grep命令

[英]Trying to simulate grep command

编译代码时出现分段错误。

如果有人可以帮助我,我不会明白我的代码有什么问题会很高兴。

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

int main(int argc,char *argv[])
{
FILE *fp;
char fline[100];
char *newline;
int i,count=0,occ=0;

fp=fopen(argv[1],"r");

while(fgets(fline,100,fp)!=NULL)
{
count++;
    if(newline=strchr(fline,'\n'))
        *newline='\0';
    if(strstr(fline,argv[2])!=NULL)
    {
        printf("%s %d %s",argv[1],count,fline);
    occ++;  
    }


}

printf("\n Occurence= %d",occ);

return 1;
}

看到男人打开男人打开

FILE *fp;
...
fp=open(argv[1],"r");

open返回一个整数,而不是文件指针。 只需将该行更改为

fp=fopen(argv[1],"r");

注意:对于那些想知道这是关于什么的人,OP从问题代码中编辑了此错误。

这导致我们(也解决了其他一些小问题-请参阅评论):

+ EDIT:指向应该进行错误检查的地方:

#include<stdio.h>
#include<string.h>
#include <errno.h>

int main(int argc, char *argv[]) {
    FILE *fp;
    char fline[100];
    char *newline;
    int i, count = 0, occ = 0;

    // for starters, ensure that enough arguments were passed:
    if (argc < 3) {
      printf("Not enough command line parameters given!\n");
      return 3;
    } 

    fp = fopen(argv[1], "r");
    // fopen will return if something goes wrong.  In that case errno will
    // contain the error code describing the problem (could be used with
    // strerror to produce a user friendly error message
    if (fp == NULL) {
      printf("File could not be opened, found or whatever, errno is %d\n",errno);
      return 3;
    } 


    while (fgets(fline, 100, fp) != NULL) {
        count++;
        if (newline = strchr(fline, '\n'))
            *newline = '\0';
        if (strstr(fline, argv[2]) != NULL) {
            // you probably want each found line on a separate line,
            // so I added \n
            printf("%s %d %s\n", argv[1], count, fline);
            occ++;
        }
    }
    // it's good practice to end your last print in \n
    // that way at least your command prompt stars in the left column
    printf("\n Occurence= %d", occ);

    return 1;
}

ps:所以错误发生在运行 时而不是编译期间 -这种区别非常关键,因为寻找编译器故障并解决库使用错误需要非常不同的技术...

暂无
暂无

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

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