EDIT:我解决了输出文件的问题(始终区分大小写)。但是分割错误的第一个问题仍然存在。
*编辑2:所以我运行了gdb,这出现了*
Program received signal SIGSEGV, Segmentation fault.
_IO_new_fclose (fp=0x0) at iofclose.c:54
54 if (fp->_IO_file_flags & _IO_IS_FILEBUF)
编辑3:显示错误是在lineCounter mygrep.c:42
上的fclose(file)处我的C程序有问题。为了提供一些信息,在第一个任务中,我们被要求在C中基于UNIX的系统中实现grep命令。我们有诸如 grep [-i] [-o outfile]关键字filename (待阅读)。
如果存在 [-i] ,则搜索的关键字将不区分大小写。
如果指定了 [-o outfile] ,则结果将写入此文件中。否则它将显示在屏幕上。
关键字是我们应该搜索的模式,文件名是将要读取的文件的名称。
一切正常,直到我尝试实现 [-o outfile] 部分,在该部分中检查是否为NULL。
在没有 [-o outfile] 的情况下,程序成功在屏幕上打印结果(不区分大小写和敏感),但最后给出 Segmentation Fault(核心已转储)尽管有效。
为使问题可视化,它是这样的:
EXAMPLE.IN具有=
ARduino
后退
ARD
mygrep -i ard example.in
此命令将打印出
ARduino
retard
ARD
Segmentation Fault(core dumped)
对大小写敏感的人也可以使用
mygrep -i ard example.in
ard
Segmentation Fault(core dumped)
我真的不知道为什么这是我不熟悉C的原因。我通常使用Java编写代码。
这是main.c方法:
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include "mygrep.h"
int main(int argc, char **argv)
{
bool caseSensitive = true;
char *outfile = NULL;
int c;
while((c= getopt(argc,argv,"io:"))!= -1)
{
switch(c)
{
case 'i' : caseSensitive = false;
break;
case 'o' : outfile = optarg;
break;
default:
break;
}
}
char *keyword = argv[optind];
char *inputfile = argv[optind+1];
mygrep(inputfile,caseSensitive,keyword,outfile);
}
mygrep.c方法:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mygrep.h"
static int lineCounter(char filename[])
{
FILE *file = fopen(filename,"r");
int lines,c;
lines = 0;
if(file)
{
while((c = getc(file)) !=EOF)
{
if(c == '\n')
{
++lines;
}
}
}
fclose(file); //** THIS IS THE LINE WHERE DEBUGGER GETS ERROR**
return lines;
}
int mygrep(char filename[],bool caseSensitive,char pattern[],char outfile[])
{
char str[100];
int lines = lineCounter(filename);
FILE *file = fopen(filename,"r");
FILE *out;
int i = 0;
if (outfile != NULL)
{
out = fopen(outfile,"w");
}
if(file == NULL)
{
perror("Error opening file");
exit(EXIT_FAILURE);
}
while(i<lines)
{
if(fgets (str,100, file)!= NULL )
{
if(caseSensitive)
{
if(strstr(str,pattern) != NULL)
{
if(outfile == NULL)
{
printf("%s",str);
} else
{
fprintf(out,"%s",str);
}
}
} else
{
if(strcasestr(str,pattern) != NULL)
{
if(outfile== NULL)
{
printf("%s",str);
} else
{
fprintf(out,"%s",str);
}
}
}
}
++i;
}
fclose(out);
fclose(file);
return 0;
}