我尝试多次读入一个文件而不是一次。 在尝试时,我遇到了很多段错误。带有 while 循环的程序部分如下所示:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
/* General use buffer */
#define STRLEN 8196
char string[STRLEN];
int lines = 1024;
char **line;
int linemax;
int longest=0;
int main(){
int len,i;
int zwei = 1;
FILE * fp;
char *s;
int debug = 0;
line=(char **)malloc(sizeof(char *) * 1024);
do{
if ( (fp = fopen("rhel7_160731_0606.nmon", "r")) == NULL) {
perror("failed to open file");
perror("fopen");
exit(75);
}
printf("where is the problem1,3\n");
for (i = 0; fgets(string, STRLEN, fp) != NULL; i++) {
if (i >= lines) {
lines += 1024;
line = (char **)realloc((void *)line, sizeof(char *) * lines);
}
if (string[strlen(string)-1] == '\n')
string[strlen(string)-1] = 0;
if (string[strlen(string)-1] == '\r')
string[strlen(string)-1] = 0;
if (string[strlen(string)-1] == ' ')
string[strlen(string)-1] = 0;
if (string[strlen(string)-1] == ',')
string[strlen(string)-1] = 0;
len = strlen(string) + 1;
if (len > longest)
longest = len;
s = malloc(len);
strcpy(s, string);
line[i] = (char *)s;
}
linemax = i;
lines = i;
if (debug)
for (i = 0; i < linemax; i++)
printf("line %d lastline %s\n", i, line[i-1]);
zwei++;
}while(zwei<4);
return 0;
}
它没有挂起或以段错误结束。
最佳答案
你好像忘记了为line
分配内存.它在这里失败:line[i] = (char *)s
.我认为你需要设置 lines
为零,因为您重新分配了 line
只有当你的迭代器 i
种植者比lines
.
另外,解决这个问题:while(zwei > 4)
至 while(zwei < 4)
.而且,您需要到free
您分配的内存 - 因为您将所有指针存储在 line
中,它不会很复杂 - 只需一个循环。
关于c - 段错误,while 循环中的 fgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39537203/