繁体   English   中英

为什么 strcat function 将指针移动到下一个字符?

[英]Why the strcat function move the pointer to the next character?

所以,我的问题很简单,我不知道为什么第一段代码不能正常工作。 程序从 pipe 读取一个 12 个字符的字符串,strcat 函数每次执行函数时都会将 buff 的指针从第一个字符移动到下一个字符,因此经过几次交互后,读取 function 使程序失败,因为缓冲区是不够大了。 使用 sprintf function 和另一个字符串解决了这个问题,但我不明白是什么导致了这个问题。 谢谢您的帮助。

int n; 
char buff[15];
close(fd[1]);
    while(n = read(fd[0],buff,12) > 0){      
        strcat(buff,"\n");
        write(1,buff,13); 
        buff[0] = '\0'; 
        }
int n; 
char buff[15];
char output[15];
close(fd[1]);
while(n = read(fd[0],buff,12) > 0){      
            sprintf(output,"%s\n",buff); 
            write(1,output,13); 
            buff[0] = '\0';       
        }

正确的代码终止缓冲区,假设它包含一个字符串读取:

int n;
char buff[15];
close(fd[1]);
while((n = read(fd[0],buff,12)) > 0){
    buff[n] = '\0'; /* add terminating null-character */
    strcat(buff,"\n");
    write(1,buff,n+1);
}

int n;
char buff[15];
char output[15];
close(fd[1]);
while((n = read(fd[0],buff,12)) > 0){
    buff[n] = '\0'; /* add terminating null-character */
    sprintf(output,"%s\n",buff);
    write(1,output,n+1);
}
  • 注意分配给n的额外()
  • 注意使用n实际读取的字符数
  • 并注意,正如迈克所说,字符串的终止。

sprintfstrcat%s说明符需要字符串,这意味着C 中的“以空字符结尾的字符序列”。

如果 pipe 中的内容不能保证为空终止,则必须添加终止空字符。

int n;
char buff[15];
close(fd[1]);
while(n = read(fd[0],buff,12) > 0){
    buff[12] = '\0'; /* add terminating null-character */
    strcat(buff,"\n");
    write(1,buff,13);
    buff[0] = '\0';
}
int n;
char buff[15];
char output[15];
close(fd[1]);
while(n = read(fd[0],buff,12) > 0){
    buff[12] = '\0'; /* add terminating null-character */
    sprintf(output,"%s\n",buff);
    write(1,output,13);
    buff[0] = '\0';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM