我是 C 的新手(很明显),我收到以下错误:
警告:传递“strncat”的参数 2 使指针来自整数而不进行强制转换 [默认启用]
代码如下:
int main(void)
{
FILE *fp;
int c;
unsigned char file[1024] = "/path/to/file";
unsigned char text[1024] = "SomeText";
fp = fopen(file, "r");
if (fp == NULL)
{
perror("Error opening file");
return(-1);
}
while ((c = fgetc(fp)) != EOF && c != '\n')
{
strncat(text,c,1);
}
}
显然这对我有意义,但不幸的是编译器不是。我怎样才能写得更好?
strncat
无法将字符附加到字符串,因为它将字符串附加到字符串。您可以从 c
字符创建一个单字符的字符串,但是使用 strcat
是一种矫枉过正:您最好创建一个指针,然后通过向其添加字符来追加:
char *p = &text[strlen(text)]; // Start appending at the last position of text
while ((c = fgetc(fp)) != EOF && c != '\n') {
*p++ = c;
if (p == &text[1023]) break;
}
*p = '\0';
已添加循环中的指针检查以处理缓冲区溢出。
我是一名优秀的程序员,十分优秀!