程序:
#include<stdio.h>
#include<string.h>
char *f_gets(char *s, int n, FILE *iop)
{
int c=0;
char *cs;
cs = s;
while (--n > 0 && (c = getc(iop)) != EOF)
{
if ((*cs++ = c) == '\n')
break;
}
*cs = '\0';
return (c == EOF && cs == s) ? NULL : s;
}
main(int argc, char *argv[])
{
FILE *fp1,*fp2;
char s2[100],s1[100];
if (argc <= 2 )
printf("2 argument needed \n");
else
if((fp1=fopen(argv[1],"r"))== NULL && (fp2=fopen(argv[2],"r"))==NULL)
printf("cat: can't open The file\n");
else
{
while(1)
{
f_gets(s1,100,fp1); // 1st iteration
f_gets(s2,100,fp2); // 2nd iteration
if(!strcmp(s1,s2))
printf("%s %s",s1,s2);
}
fclose(fp1);
fclose(fp2);
}
}
输出:
$ ./a.out a b
Segmentation fault (core dumped)
$
在上面的程序中,当我们第二次调用 f_gets 时发生了段错误。即使我两次检查程序也很难 找到问题所在。有没有人解释为什么它会产生问题。
最佳答案
您调用电话时您的第二个文件未打开。
问题是您从短路的路径调用 fopen
:
if((fp1=fopen(argv[1],"r"))== NULL && (fp2=fopen(argv[2],"r"))==NULL)
由于您的代码中存在错误,当fp1
正常打开时,fp2
将始终保持关闭状态。这是因为 (fp1=fopen(argv[1],"r"))== NULL
将评估为 0
,并确保 (fp2=fopen (argv[2],"r"))==NULL
永远不会被调用。
您可以通过将 &&
替换为 ||
来解决此问题,但更好的方法是一次打开一个文件。
关于c - getc 函数产生段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36496299/