简体   繁体   English

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

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

So, my problem is pretty simple, I don't know why the first segment of code does not work properly.所以,我的问题很简单,我不知道为什么第一段代码不能正常工作。 The program read a string of 12 characters from a pipe and the strcat fuction moves the pointer of buff from the first character to the next every time the fuction is executed and so after a few interactions the read function make the program fail because the buffer is not big enough anymore.程序从 pipe 读取一个 12 个字符的字符串,strcat 函数每次执行函数时都会将 buff 的指针从第一个字符移动到下一个字符,因此经过几次交互后,读取 function 使程序失败,因为缓冲区是不够大了。 Using the sprintf function and another string solve the issue but i don't understand what cause the problem.使用 sprintf function 和另一个字符串解决了这个问题,但我不明白是什么导致了这个问题。 Thanks for the help.谢谢您的帮助。

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';       
        }

The proper code terminates the buffer, which is assumed to contain a string read:正确的代码终止缓冲区,假设它包含一个字符串读取:

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);
}

and

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);
}
  • Note the extra ( and ) in the assignment to n注意分配给n的额外()
  • Note the use of n , the actual number of characters read注意使用n实际读取的字符数
  • And note, as Mike said, the termination of the string.并注意,正如迈克所说,字符串的终止。

strcat and %s specifier of sprintf expects strings , which means " null-terminted sequence of characters" in C. sprintfstrcat%s说明符需要字符串,这意味着C 中的“以空字符结尾的字符序列”。

If the contents from the pipe is not guaranteed to null-terminated, you have to add terminating null-character.如果 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