【发布时间】:2020-04-19 15:18:41
【问题描述】:
在我的代码中,我试图读取一个文件,读取它的行并将它们放入一个字符串数组中,然后打印它们并关闭文件。当我运行它时,它因段错误而失败并跳过文件的最后一行,我就是找不到问题... 我的直觉是错误地读取数组或文件行为不端......我是对的吗? 任何帮助或重定向都会有所帮助。 谢谢!
这里是主文件:
#include "files_utils.h"
int main()
{
FILE *fp = fopen("expl", "r");
if (!fp)
return -1;
long lines_count = countlines(fp);
long flen = file_length(fp);
String *lines = calloc(lines_count, sizeof(String));
printf("file length: %ld\n", flen);
printf("file lines: %ld\n", lines_count);
getlines(lines, lines_count, fp);
printf("finished\n");
for (String *sp = lines; sp != NULL; sp++)
printf("%s", *sp);
printf("before close\n");
fclose(fp);
printf("closed\n");
return 0;
}
这是 files_utils 文件:
#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 10
typedef char *String;
long file_length(FILE *fp)
{
/*
find the length of the file fp points to, regardless of the current position.
*/
long original_pos = ftell(fp), i = 0;
rewind(fp);
// count chars:
for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
i++;
// return the file to it's original position
fseek(fp, original_pos, SEEK_SET);
return i;
}
long countlines(FILE *fp)
{
/*
find the amount of lines in file fp points to, regardless of the current position.
*/
long original_pos = ftell(fp), i = 0;
rewind(fp);
// find newlines:
for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
if (c == '\n')
i++;
// return the file to it's original position
fseek(fp, original_pos, SEEK_SET);
return i;
}
String *getlines(String lines[], long maxlines, FILE *fp)
{
for (int i = 0; i <= maxlines; i++)
{
lines[i] = calloc(MAXLINE, sizeof(char));
fgets(lines[i], MAXLINE, fp);
}
return lines;
}
然后输出
file length: 144
file lines: 21
finished
... all the lines of the file except of the last one ...
Segmentation fault (core dumped)
【问题讨论】:
-
这个
for (int i = 0; i <= maxlines; i++)应该是这个for (int i = 0; i < maxlines; i++)吗? -
读取文件以检查其大小是一种反模式。就此而言,以任何方式检查大小(除了用于报告文件大小的实用程序)几乎是一种反模式。您应该读取文件直到 EOF,根据需要增加数据结构。
-
@WilliamPursell 我不一定同意后半部分。尤其是,增长数据结构的效率可能远低于一开始就构建合适大小的数据结构。
标签: c segmentation-fault