我在课堂作业中使用油灰,而且我有一个分段错误



编写一个C程序,计算输入文本文件中非空白字符的数量。程序将输入文件(以及带有选项-f的输出文件(的名称作为命令参数。根据选项标志,它在标准输出上显示输出,或将输出写入输出文件。(25分(

命令格式如下:

命令-f输入文件输出文件

或者,

命令的输入文件

-f表示对输出文件的写入
-s表示在屏幕上显示输出。

我在-s命令上接收到分段故障

#include <stdio.h>
#define BLANK ' '
#define NEWLINE 'n'
int main(int argc, char *argv[])
{
FILE *infile;
char c;
int char_count=0;
FILE *outfile;
outfile = fopen(argv[3], "w");
//checks for the argc length to be within the correct perameteres
if ((argc < 3) || (argc > 4))
{
printf("Incorrect format, please try gainn");
exit(1);
}

//checks the input file to see if it is empty
if ( (infile= fopen(argv[2], "r")) == NULL)
{
fprintf(stderr,"%s: cannot open %s n", argv[0], argv[1]);
exit(1);
}
// count the number of charecters in infile
while ( (c = getc(infile)) != EOF)
if ((c != BLANK) && (c != NEWLINE) )
char_count++;
//checks to see if the command is -s or not, outputing the corrct message to the  desired location
if (argv[1] == "-s")
{
printf("%d charactersn", char_count);
}
else
{
fprintf(outfile, "%s contains %d charactersn", argv[2],  char_count);
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BLANK ' '
#define NEWLINE 'n'
int main(int argc, char *argv[])
{
FILE *infile;
FILE *outfile;
char c;
int char_count=0;
//checks for the argc length to be within the correct perameteres
if ((argc < 3) || (argc > 4))
{
printf("Incorrect format, please try gainn");
exit(1);
}
//checks if passed second argument is valid (-f or -s)
if (strcmp(argv[1], "-f") == 0) {
if (argc < 4) {
fprintf(stderr, "Please inform output file. Usage: -f inputfile outputfile");
exit(1);
}
outfile = fopen(argv[3], "w");
}
else if (strcmp(argv[1], "-s") != 0) {
fprintf(stderr, "Parameter not recognized: %sn", argv[1]);
exit(1);
}
//checks the input file to see if it is empty
if ( (infile= fopen(argv[2], "r")) == NULL)
{
fprintf(stderr,"%s: cannot open %s n", argv[0], argv[1]);
exit(1);
}
// count the number of charecters in infile
while ( (c = getc(infile)) != EOF)
if ((c != BLANK) && (c != NEWLINE) )
char_count++;
//checks to see if the command is -s or not, outputing the corrct message to the  desired location
if (strcmp(argv[1], "-s") == 0)
{
printf("%d charactersn", char_count);
}
else
{
fprintf(outfile, "%s contains %d charactersn", argv[2],  char_count);
printf("Result written to %sn", argv[3]);
}
return 0;
}

相关内容

最新更新