【发布时间】:2020-04-18 21:39:52
【问题描述】:
我对 C 比较陌生,我正在使用 getline() 函数来读取作为标准输入提供的文件的内容。
但是,while 循环不会读取文件的第一行,我不知道为什么!
对于上下文:文件读取-
a b c -d e F输出正确地读取和拆分-d、e和f,但仅在while循环之外打印a b c。
int main (){
//utilising data provided at http://www.linux.die.net/man/3/getline
//char*linePointer is initialized to NULL, for getline() to allocate a buffer that stores the line
//buffer gets resized dynamically
char *linePointer = NULL;
size_t len = 0;
//checks if the file is empty and prints -, if it is
if ((getline(&linePointer, &len, stdin) == -1)){
printf("-\n");
}
//as long as the stream is valid, and the file can be read
//if either of the conditions are not satisfied then while loop condition is not satisfied
//prints the contents of the line
Clauses cs = createNewArrayList();
printf("%s\n", linePointer);
while ((getline(&linePointer, &len, stdin) != -1)){
printf("%s\n", linePointer);
Clause c = createNewArrayList();
char *token;
char *delim = " ";
token = strtok(linePointer, delim);
while (token != NULL){
char *duplicate = strdup(token);
add(c, duplicate);
printf("%s\n",duplicate);
token = strtok(NULL, delim);
}
add(cs, c);
}
free(linePointer);
exit(EXIT_SUCCESS);
【问题讨论】:
-
您正在泄漏正在读取的第一行。您应该使用
do..while循环而不是while循环。您还泄漏了每个duplicate令牌。 -
@RemyLebeau It's a standard POSIX function.
-
@nicksheen 不,它没有。阅读
getline的文档。 -
@JosephSible-ReinstateMonica 你是对的,对不起。我刚看了第一段