读取行直到 EOF 到 C 中的指针
Read lines until EOF into pointer in C
我知道关于它的话题有几百个,但我需要再问一遍。
我有以下代码:
char *str;
while(fgets(&str,50,stdin) != NULL && &str != EOF) {
printf(&str);
}
printf("Test");
我想阅读我的代码中的几行代码并对其进行处理。在那个例子中,它只是打印。
我想在有 EOF 时结束,然后在 while 循环之后做其他事情。
不幸的是,在我使用 CMD-D(mac/CLion 上的 EOF)的那一刻,无论后记是什么,整个程序都终止了,所以输出中不再有 "Test"。
有谁知道发生了什么事吗?另请注意,我需要它作为字符指针,因为我想稍后使用它。
您的代码应如下所示:
char str[50];
while(fgets(str,sizeof(str),stdin) != NULL) {
printf("%s",str);
}
printf("Test");
在您的代码中,str
只是一个不指向已分配内存的指针。然后你要求 fgets()
将它读取的内容存储在 str
中(但是存储在哪里,因为没有为 str
分配内存?!)。这会导致未定义的行为,必须修复。
一个简单的解决方案是 str
一个字符数组。
您的代码中的 EOF
表明您没有阅读该函数的手册,其中指出:
Return value:
If the end-of-file is encountered while attempting to
read a character, the eof indicator is set (feof). If this happens
before any characters could be read, the pointer returned is a null
pointer (and the contents of str remain unchanged).
这意味着我们不需要额外检查。
把所有东西放在一起:
#include <stdio.h>
int main()
{
char str[50];
while (fgets(str, 50, stdin)) {
printf("%s\n", str);
}
return 0;
}
逐行读取文件,然后打印每一行。
有用link:Removing trailing newline character from fgets() input。
PS:您可以使用 fgets()
sizeof(str)
作为第二个参数,而不是 50(数组的大小),但是当 str
是一个指针,它实际上指向内存存储的另一个位置(例如另一个数组)。
我知道关于它的话题有几百个,但我需要再问一遍。 我有以下代码:
char *str;
while(fgets(&str,50,stdin) != NULL && &str != EOF) {
printf(&str);
}
printf("Test");
我想阅读我的代码中的几行代码并对其进行处理。在那个例子中,它只是打印。 我想在有 EOF 时结束,然后在 while 循环之后做其他事情。 不幸的是,在我使用 CMD-D(mac/CLion 上的 EOF)的那一刻,无论后记是什么,整个程序都终止了,所以输出中不再有 "Test"。
有谁知道发生了什么事吗?另请注意,我需要它作为字符指针,因为我想稍后使用它。
您的代码应如下所示:
char str[50];
while(fgets(str,sizeof(str),stdin) != NULL) {
printf("%s",str);
}
printf("Test");
在您的代码中,str
只是一个不指向已分配内存的指针。然后你要求 fgets()
将它读取的内容存储在 str
中(但是存储在哪里,因为没有为 str
分配内存?!)。这会导致未定义的行为,必须修复。
一个简单的解决方案是 str
一个字符数组。
您的代码中的 EOF
表明您没有阅读该函数的手册,其中指出:
Return value:
If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged).
这意味着我们不需要额外检查。
把所有东西放在一起:
#include <stdio.h>
int main()
{
char str[50];
while (fgets(str, 50, stdin)) {
printf("%s\n", str);
}
return 0;
}
逐行读取文件,然后打印每一行。
有用link:Removing trailing newline character from fgets() input。
PS:您可以使用 fgets()
sizeof(str)
作为第二个参数,而不是 50(数组的大小),但是当 str
是一个指针,它实际上指向内存存储的另一个位置(例如另一个数组)。