我不断收到段错误。我发现它发生在这两行之间:
printf("%s - File exists!\n", file_name);
printf("inforloop");
但我不确定为什么段错误不断发生。 这是整个代码:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
FILE *fp;
char err_message[128], file_name[128];
int main(int argc, char *argv[])
{
if(argc <= 2)
{
printf("ERROR : Usage %s <file name>\n", argv[0]);
return 1;
}
int i = 1;
for(i; i< argc; i++)
{
strcpy(file_name, argv[i]);
if ((access(file_name, F_OK)) != -1)
{
printf("begining of for loop\n");
printf("%s - File exists!\n", file_name);
printf("inforloop");
fclose(fp);
}
else
{
sprintf(err_message, "open %s", file_name);
perror(err_message);
}
}
return 0;
}
结果:
1
begining of for loop
date.txt - File exists!
Segmentation fault (core dumped)
最佳答案
您正在fclose
使用fp
,而您从未fopen
编辑过它,甚至从未对其进行过初始化。
输出在打印 inforloop
之前被切断,因为您的标准输出是行缓冲的,并且 inforloop
之后没有换行。
关于C - 某处段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35166685/