C - 某处段错误

标签 c

我不断收到段错误。我发现它发生在这两行之间:

            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/

相关文章:

c - 为什么我不能用 wchar_t 在 c 中打印 unicode 字符?

c - 如何使多个子进程暂停直到发送信号

C - 函数未计算给定字符的正确数量

c - 如果 a 的值为 5,a++ + a 的值是多少?

javascript - 浏览器中的mp3流解码

c - 为什么指向函数指针的指针是8字节?

iphone - 动画后cocos2d自动删除 Sprite

c - 如何通过更改其成员的顺序找到所有可以变得更小的结构

K&R 书中的 C 编程练习

c - 就套接字 API 而言,主动关闭与被动关闭?