[英]C strcmp() not returning 0 as expected
我已经尝试使用strcmp在下面的程序中返回true了很多天了,我已经阅读了strcmp的手册页,进行了读取,编写...我也遇到了同样的问题。 以下源代码只是一个测试程序,它使我感到沮丧,其中一些注释掉的行是我为使strcmp正常工作而进行的其他尝试。 我已经用'gdb -g'进行了编译,并且一次完成了一条指令。 printf语句几乎可以说明整个故事。 我无法获得buf或bufptr的值等于“ t”。 我简化了程序,让它一次又一次地在屏幕上打印一个字符,并且它们从读取的任何文件中按预期方式打印,但是,一旦我开始玩strcmp,事情就会变得疯狂。 我一生都无法找到一种方法来获取buf中的值成为我期望的唯一字符。 当简化为仅write(1,...)调用时,它将预期的单个char写入stdout,但是strcmp变为单个't'永远不会返回0。 先感谢您。 我最初没有bufptr在那里,正在对buf本身进行strcmp,还尝试使用bufptr [0] = buf [0],但仍然不一样。
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#define BUF_SIZE 1
void main(int argc, char *argv[])
{
char buf[BUF_SIZE];
int inputFd = open(argv[1], O_RDONLY);
char tee[] = "t";
int fff = 999;
char bufptr[BUF_SIZE];
// char *bufptr[BUF_SIZE];
while (read(inputFd, buf, BUF_SIZE) > 0) {
bufptr[0] = buf[0];
// bufptr = buf;
printf("********STRCMP RETURNED->%d\n", fff); // for debugging purposes
printf("--------tee is -> %s\n", tee); // for debugging purposes
printf("++++++++buf is -> %s\n", buf); // " " "
printf("@@@@@@@@bufptr is -> %s", bufptr); // " " "
write (1, buf, BUF_SIZE);
if ((fff = strcmp(tee, bufptr)) == 0)
printf("THIS CHARACTER IS A T");
}
close(inputFd);
}
函数str
-family将字符串作为输入,这些字符串是存储以null结束的字符序列的数组。 但是,您不能在缓冲区中为空字符提供空间。 要使缓冲区成为字符串,您需要为空字符添加空间并将值归零,以便它们以空字符结尾。
void main(int argc, char *argv[])
{
char buf[ BUF_SIZE + 1 ] = {0};
int inputFd = open(argv[1], O_RDONLY);
char tee[] = "t";
while (read(inputFd, buf, BUF_SIZE) > 0) {
if ( strcmp( tee, buf ) == 0 )
printf("THIS CHARACTER IS A T");
}
close(inputFd);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.