PuTTY 上的分段错误

Segmentation fault on PuTTY

我有学校的作业,要求我在 PuTTY 上编写 c program,我已经完成了我的代码,然后代码执行得很完美,编译器没有任何抱怨,但我出现分段错误。请帮忙!

This is the assignment

These are commands which I typed from PuTTY

这是源代码:

#include <stdio.h>
#include <string.h>
#define BLANK ' '
#define NEWLINE '\n'
int main (int argc, char *argv[])
{ 
    FILE *infile;
    char c;
    int char_count = 0;

infile = fopen(argv[2], "r");

if(infile = NULL)
{
    fprintf(stderr, "%s: Cannot open %s \n", argv[0], argv[2]);
    exit(1);
}
    
while ( (c = getc(infile)) != EOF)
    if ((c != BLANK) && (c != NEWLINE) )
        char_count++;
   
    if (argc == 3)
    {
        if(strcmp(argv[1], "-s") == 0)
            {   
                printf ("%d characters\n", char_count);
            }
    }
    else if (argc == 4)
    {
        if(strcmp(argv[1], "-f") == 0)
        {
            FILE *outfile;
            outfile = fopen(argv[3], "w");
            if(outfile == NULL)
            {
                printf("error cannot open file");
                exit(1);
            }
            fprintf (outfile, "My file has %d chars\n", char_count);
        }
    }
    

return 0; }

你打错了:
if(infile = NULL)
它将 NULL 分配给 infile,并且 if 变为 if (NULL),这永远不会是真的。 在这一行 infile 之后是 NULL,但程序继续并尝试从 NULL 文件中读取。

修复:
if (infile == NULL)