[英]Making myfgets using char pointer as an input
char *myfgets(char *s, int n, FILE *in) {
char ch;
if (n<=0) {
return s;
}
while (((ch = getc(in)) != '\n')) {
if(ch == EOF){
return NULL;
}
else if (ch == '\n') {
break;
} else {
*s=ch;
s++;
}
}
*s = '\n';
if (ferror(in) != 0) {
return NULL;
} else {
return s;
}
if (strlen(s) > 512) {
return NULL;
}
}
I want to take 1 line only from some specific file and put the line into the char pointer ( *s
).我只想从某个特定文件中取出 1 行并将该行放入字符指针 ( *s
) 中。 I made this function but when I run the program it didn't work really well.我做了这个 function 但是当我运行这个程序时它并没有很好地工作。 For the result, there are a lot of unknown characters that are displayed.结果,显示了很多未知字符。
Is there anything wrong with my code?我的代码有什么问题吗?
From the man page of strlen()
:从strlen()
的手册页:
The
strlen()
function calculates the length of the string pointed to bys
, excluding the terminating null byte ('\0'
).strlen()
function 计算s
指向的字符串的长度,不包括终止字节 null ('\0'
)。
So, strlen
counts the number of characters until it finds a null byte '\0'
, and not the newline character '\n'
.因此, strlen
计算字符数,直到找到 null 字节'\0'
,而不是换行符'\n'
。 Consider changing考虑改变
*s = '\n'
to到
*s = '\0'
Alternatively, you could write your own strlen
that looks for '\n'
instead of '\0'
.或者,您可以编写自己的strlen
来查找'\n'
而不是'\0'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.