调用getc时为什么会出现分段错误?

时间:2015-03-09 01:58:48

标签: c stdio

// Program to remove the comments and the spaces from the given input file
#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    FILE *input_file, *output_file;

    input_file = fopen("input", "r");
    output_file = fopen("output", "w");

    char c1,c2;

    c1 = getc(input_file); // taking the first character of the file
    c2 = getc(input_file); // Shows segmentation fault here

    while(c1 != EOF)
    {
        if(c1 == '/' && c2 == '/') // if it is a single line comment
        {
            c1 = getc(input_file);


            while(c1 != '\n') // keep scanning until \n character is found
            {
                c1 = c2;
                c2 = getc(input_file);
            }
        }

       else if(c1 == '/' && c2 == '*') // for multi line comment
        {
            while(c1 != '*' && c2 != '/')
            {
                c1 = c2;
                c2 = getc(input_file);
            }

            c1 = getc(input_file);
            c2 = getc(input_file);
        }

        else if(c1 == '\n' && c2 == '\n') // to remove extra newline characters
            while(c1 == '\n')
                c1 = getc(input_file);

        else if(c1 == ' ' && c2 == ' ') // to remove extra whitespaces
            while(c1 == ' ')
                c1 = getc(input_file);
        else
            putc(c1, output_file);

        c1 = c2;
        c2 = getc(input_file);
    }
}

我正在尝试从输入文件中删除注释和空格。但是,当我在Windows 8中的代码块中使用GCC编译器运行此代码时,它将停止工作。

编译此程序时,没有显示错误但执行它会停止工作。

我尝试运行调试器,它在代码中标记的行中显示分段错误。

编辑:

我再次检查并发现input_file是一个NULL指针。 但是,我在项目文件夹中有一个名为input(.txt)文件的文件。 为什么它是一个NULL指针呢?

1 个答案:

答案 0 :(得分:3)

inputinput(.txt)是不同的文件名(如果您的意思是input.txt)。您需要指定文件的确切名称。

当然,在尝试对其进行任何读/写操作之前,您应该检查input_file并且output_file不是NULL。如果它们为null,那么您可以通过errno检查perror,或者通过input_file = fopen("input.txt", "r"); if ( !input_file ) { perror("Failed to open input file: "); exit(EXIT_FAILURE); } 函数,例如:

,来了解出了什么问题。
c1

其他问题:

  • c2int必须包含EOF类型。这是因为fgetc是任何有效字符值的带外(由while(c1 != '\n')返回)。
  • while和下一个c1 != EOF循环中,您还需要检查\n否则如果文件结束发生在{{1}之前,这将是一个无限循环}}。