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

Why do I get a segmentation fault when calling getc?

// 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 指针?

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

当然,在尝试对它们执行任何 read/write 操作之前,您应该检查 input_fileoutput_file 不是 NULL。如果它们为空,那么您可能会通过检查 errno 或通过 perror 函数,例如:

来了解问题出在哪里
input_file = fopen("input.txt", "r");
if ( !input_file )
{
    perror("Failed to open input file: ");
    exit(EXIT_FAILURE);
}

其他问题:

  • c1c2 必须具有类型 int。这是因为 EOF 超出任何有效字符值(由 fgetc 返回)。
  • while(c1 != '\n') 和下一个 while 循环中,您还需要检查 c1 != EOF 否则如果文件结束发生在 \n.