我的目标是将文件的非注释行打印到屏幕或输出文件,无论如何指定。我的代码在两种情况下工作正常(即我得到了所需的输出)但是,当我将线条打印到屏幕上时,它工作正常,并且在打印完所有内容后,它显示Segmentation fault (core dumped)
这是我的代码:
/* Assignment 1 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define MAXS 256
int main(int argc, char *argv[])
{
FILE *fp;
FILE *op;
char line[MAXS] = {0};
int max_x, max_y, num_pt, rand_inst;
int ch;
int inputfile = 0, outputfile = 0;
int i;
for (i = 1; i < argc; i++)
{
if (strcmp (argv[i], "-i") == 0)
inputfile = i+1;
if (strcmp (argv[i], "-o") == 0)
outputfile = i+1;
}
if (inputfile == 0)
{
/* invalid command line options */
printf("\nIncorrect command-line...\n");
printf("> %s [-i inputfile [-o outputfile]]\n\n", argv[0]);
exit(0);
}
fp = fopen(argv[inputfile], "r");
if (fp == 0)
{
printf("\nCould not find %s\n", argv[inputfile]);
exit(0);
}
/* while ((ch = fgetc(fp)) != EOF)) */
/* This part is where I get the error but I get the desired output */
if (outputfile == 0)
{
while (fgets (line, MAXS, fp) != NULL)
{
char *p = line;
size_t len = strlen (line);
while (len > 0 && (line[len-1] == '\n' || line[len-1] == '\r'))
line[--len] = 0; /* strip newline or carriage rtn */
while (isspace (*p)) /* advance to first non-whitespace */
p++;
/* skip lines beginning with '#' or blank lines */
if (*p == '#' || !*p)
continue;
printf("%s\n", line);
}
}
else
{
op = fopen(argv[outputfile], "w");
while (fgets (line, MAXS, fp) != NULL)
{
char *p = line;
size_t len = strlen (line);
while (len > 0 && (line[len-1] == '\n' || line[len-1] == '\r'))
line[--len] = 0; /* strip newline or carriage rtn */
while (isspace (*p)) /* advance to first non-whitespace */
p++;
/* skip lines beginning with '#' or blank lines */
if (*p == '#' || !*p)
continue;
fprintf(op, "%s\n", line);
}
}
fclose(op);
return 0;
}
这是输出,它给我分段错误:
100 100
10
0 0
0 90
70 100
100 50
30 30
30 70
<70> 70 7070 30
50 50
45 0
分段错误(核心转储)
然而,上面是所需的输出减去分段故障错误
我知道分段错误与读取/写入非法内存位置有关,但我无法弄清楚为什么程序给我错误,前提是我没有编译错误而且我得到了期望的输出
语言:c99;编译器:gcc
答案 0 :(得分:4)
seg错误是由您的上一行op
引起的。我怀疑NULL
是fclose
或无效的内存位置(即垃圾),这导致了seg错误。
除了在else
语句中粘贴bool check(int wins[], int number)
{
for (int i = 0; i <= arraySize; ++i)
if (number == wins[i])
{
return true;
}
else if (number != wins[i])
{
return false;
}
}
(如评论中所述)...我还会初始化这些文件指针。