【发布时间】:2017-07-30 05:50:06
【问题描述】:
我有以下函数从文件中读取单词并使用 fgets 和 strtok 输出每个单词,其中文件中的单词由换行符分割:
word1
word2
word3
我正在尝试模仿文件中的单词位于仅由空格分隔的单行的功能:
word1 word2 word3
但是,我似乎只能在将 strtok 字符更改为“”并尝试读取单行时获得第一个单词。我不确定我错过了什么。
#include <string.h>
#include <malloc.h>
int readLines;
char *output[255];
char *filename = "commands.txt";
char fileRead(const char *filename, char *output[255])
{
int count = 0;
char input[255];
char *line;
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Cannot open file: %s\n", filename);
} else {
while(count < 255 && fgets(input, sizeof(input), file)) {
line = strtok(input, "\n");
if (line) {
output[count++] = strdup(line); /* Store replica */
}
}
fclose(file);
}
return count;
}
char *strdup(const char *str)
{
char *ret = malloc(strlen(str)+1);
if (ret) {
strcpy(ret, str);
}
return ret;
}
int main(int argc, char *argv[])
{
readLines = fileRead(filename, output);
/* read from array and pass into flag function */
for (int x = 0; x < readLines; ++x) {
printf("%s\n", output[x]);
free(output[x]);
}
return 0;
}
【问题讨论】:
-
你需要在
strtok()上循环。第一次调用将提供input作为strtok()的第一个参数;随后的NULL。 -
@JonathanLeffer 啊,对了,谢谢
-
错误消息应该输出到
stderr,而不是stdout,并且当错误来自系统函数时,应该使用perror(),它会输出包含的文本和相应的系统错误信息。通常最好的办法是在显示消息后调用exit(),而不是让程序继续运行 -
拥有一个名称(和整体签名)与系统函数相同的本地函数是一种糟糕的编程习惯。注意
strdup()是包含头文件string.h时暴露的系统函数 -
发布的代码存在大量内存泄漏。 (或者,换句话说,代码应该总是在自己之后清理。)代码应该为通过
strdup()获得的每个char数组调用free()