【发布时间】:2011-02-16 20:20:12
【问题描述】:
对于一个类,我必须编写一个程序来读取文本文件,格式为:
T A E D Q Q
Z H P N I U
C K E W D I
V U X O F C
B P I R G K
N R T B R B
退出
快速
棕色
狐狸
我正在尝试将字符放入一个字符数组中,每一行都是它自己的数组。 我可以从文件中读取,这是我用来解析文件的代码:
char** getLinesInFile(char *filepath)
{
FILE *file;
const char mode = 'r';
file = fopen(filepath, &mode);
char **textInFile;
/* Reads the number of lines in the file. */
int numLines = 0;
char charRead = fgetc(file);
while (charRead != EOF)
{
if(charRead == '\n' || charRead == '\r')
{
numLines++;
}
charRead = fgetc(file);
}
fseek(file, 0L, SEEK_SET);
textInFile = (char**) malloc(sizeof(char*) * numLines);
/* Sizes the array of text lines. */
int line = 0;
int numChars = 1;
charRead = fgetc(file);
while (charRead != EOF)
{
if(charRead == '\n' || charRead == '\r')
{
textInFile[line] = (char*) malloc(sizeof(char) * numChars);
line++;
numChars = 0;
}
else if(charRead != ' ')
{
numChars++;
}
charRead = fgetc(file);
}
/* Fill the array with the characters */
fseek(file, 0L, SEEK_SET);
charRead = fgetc(file);
line = 0;
int charNumber = 0;
while (charRead != EOF)
{
if(charRead == '\n' || charRead == '\r')
{
line++;
charNumber = 0;
}
else if(charRead != ' ')
{
textInFile[line][charNumber] = charRead;
charNumber++;
}
charRead = fgetc(file);
}
return textInFile;
}
这是我的程序的运行:
欢迎使用 Word 搜索!
输入您希望我们解析的文件:testFile.txt TAEDQQ!ZHPNIU!CKEWDI!VUXOFC!BPIRGK!NRTBRB!退出!THE!QUICK!BROWN!FOX 分段错误
发生了什么事? A),为什么那里有感叹号,B)为什么最后会出现段错误?我主要做的最后一件事是遍历数组/指针。
【问题讨论】:
-
第一次读取文件只是为了调整数组的大小是一种非常低效的方法。也许您可以使用一种不需要您事先知道需要放入多少数据的数据结构? (提示)
-
嗯,这是 C 类的介绍。我们只介绍了指针/数组/其他简单的东西。我更喜欢使用更好的数据结构,但我不知道我的选择是什么(我不确定是否会受到鼓励——我认为我们应该只用简单的操作来完成这个程序)。 :\
-
请注意,由于文件使用的是
\r\n,因此您目前正在对使用 dos 样式行尾的文件重复计算行数。
标签: c file pointers segmentation-fault