我已经写了一些代码来读取每行文本文件到2d数组。
/* FileProcess.c library */
#define LINE_SIZE 128 /* Max line's length = 256 characters */
extern ulong
File_ReadLine (FILE *fptr,
char **result)
{
char buff_line[LINE_SIZE], *p;
ulong nLines = 0UL;
/* Check if fptr is readable */
if (fptr == NULL) {
printf("File not found.\n");
return -1;
}
/*get number of lines; from http://stackoverflow.com/a/3837983 */
while (fgets(buff_line, LINE_SIZE, fptr))
if (!(strlen(buff_line) == LINE_SIZE-1 && buff_line[LINE_SIZE-2] != '\n'))
nLines++;
/* Allocating memory for result */
result = malloc(nLines * sizeof(char *)); //
/* Pointer return to begin of file */
rewind(fptr);
/* Getting lines */
int i = 0;
while (!feof(fptr)) {
/* Get current line to buff_line */
fgets(buff_line, LINE_SIZE, fptr);
/* Replace '\n' at the end of line */
char *c = strchr(buff_line, '\n');
if (c != NULL)
*c = '\0';
/* Handle '\n' at the end of file */
if (feof(fptr))
break;
/* Memory allocate for p */
result[i] = malloc (LINE_SIZE * sizeof(char));
/* Copy buff_line to p */
strcpy(result[i], buff_line);
i++;
}
return (nLines);
}
主程序:
int main ()
{
char **Phone;
FILE *fptr;
fptr = fopen("phone.na.txt", "r");
ulong nLines = File_ReadLine(fptr, Phone);
printf("%ld\n", nLines);
int i;
for (i = 0; i < nLines; i++) {
printf("%s", Phone[i]);
}
fclose(fptr);
return 1;
}
使用gdb,逐行运行,程序后返回分段故障 printf(“%s”,Phone [i]); 所以我无法理解为什么这里的分段错误? malloc()有错误吗?
答案 0 :(得分:0)
我没有编译或运行代码,但我认为问题出在您的行计数器中:
while (fgets(buff_line, LINE_SIZE, fptr))
if (!(strlen(buff_line) == LINE_SIZE-1 && buff_line[LINE_SIZE-2] != '\n'))
nLines++;
你在这里说的是除非“buff_line的字符串长度等于LINE_SIZE -1且buff_line [LINE_SIZE-1]的字符不等于'\ n'”,否则增加nLines。
所以......每当你从文本文件中读出一行以'\ n'结尾,并且该行长度为127个字符时,你就不会增加nLines。你为nLines设置了malloc空间,但是你可能会从你的文件中读取多于nLines的数据...那时,你写的结果比你分配的更多,而且坏事情会发生