#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
include <getopt.h>
#define DEFAULT_STRING_NUM 10 /*default number lines */
#define MAXLEN 2000 /* max number of the array */
#define MAXLINES 1024 /* max number lines */
char *lineptr[MAXLINES];
int main(int argc, char *argv[])
{
int n;
int c;
FILE *fp = NULL;
char *arr[2000];
int len = 0;
char buffer[1024] = {'\0'};
char *str;
int i = 0, j, k;
c = getopt (argc, argv, "n:");
if (c == 'n')
sscanf ( argv[2], "%d", &n);
else
n = 10;
fp = fopen ("input.txt", "r");
while (fgets (buffer, 1024, fp) != NULL)
{
len = strlen (buffer);
str = malloc (len+1);
strcpy (str, buffer);
if (arr[i%n] )
{
free (arr[i%n]);
arr[i%n] = NULL;
}
arr[i%n] = str;
i++;
memset (buffer, '\0', 1024);
}
k = i - 1;
for (j=k; j<n+k; j++)
printf ("%s", arr[j%n]);
return 0;
}
我在
上存在细分错误while (fgets (buffer, 1024, fp) != NULL)
答案 0 :(得分:0)
fgets()导致分段错误,因为先前对fopen()的调用失败。检查从fopen()返回的值。如果为NULL,请不要尝试执行I / O。相反,请查看errno以查看为什么无法打开文件。
答案 1 :(得分:0)
执行此操作
(gdb) i r $rip
rip 0x5555555546b2
0x5555555546b2 <main+8>
这会告诉您为什么文件无法打开