#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "termios.h"
int main (int ac, char* av[]) {
struct termios ttyinfo;
int result;
result = tcgetattr(0, &ttyinfo);
if (result == -1) {
perror("cannot get params about stdin");
exit (1);
}
if (av[1] == "stop" && av[2] == "A") {
printf ("Stop: ^%c\n", ttyinfo.c_cc[VSTOP] - 19 + 'A');
}
if (av[1] == "start" && av[2] == "^Q") {
printf ("Stop: ^%c\n", ttyinfo.c_cc[VSTOP] - 3 + 'A');
}
return 0;
}
我正在学习Linux,这段代码用C语言编写。使用命令行显示字符更改。例如:./示例停止A.但是,它不会在屏幕上显示任何内容。
答案 0 :(得分:3)
使用C时应该打开警告,你很可能会发现失败的原因。如果你用它来用Clang编译它
gcc -Wall -std=c11 -pedantic goo.c
你会遇到这些错误:
goo.c:19:13: warning: result of comparison against a string literal is unspecified (use strncmp instead) [-Wstring-compare]
if (av[1] == "stop" && av[2] == "A")
^ ~~~~~~
goo.c:19:32: warning: result of comparison against a string literal is unspecified (use strncmp instead) [-Wstring-compare]
if (av[1] == "stop" && av[2] == "A")
^ ~~~
goo.c:24:13: warning: result of comparison against a string literal is unspecified (use strncmp instead) [-Wstring-compare]
if (av[1] == "start" && av[2] == "^Q")
^ ~~~~~~~
goo.c:24:33: warning: result of comparison against a string literal is unspecified (use strncmp instead) [-Wstring-compare]
if (av[1] == "start" && av[2] == "^Q")
您需要使用字符串比较函数比较字符串。您无法使用==
按照您的方式比较字符串。尝试这样的事情:
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "termios.h"
int main (int ac, char* av[])
{
struct termios ttyinfo;
int result;
result = tcgetattr(0, &ttyinfo);
if (result == -1) {
perror("cannot get params about stdin");
exit (1);
}
if(ac > 2) {
if (strcmp(av[1], "stop") == 0 && strcmp(av[2], "A") == 0) {
printf ("Stop: ^%c\n", ttyinfo.c_cc[VSTOP] - 19 + 'A');
}
if (strcmp(av[1], "start") == 0 && strcmp(av[2], "^Q") == 0) {
printf ("Stop: ^%c\n", ttyinfo.c_cc[VSTOP] - 3 + 'A');
}
}
else {
printf("Need two arguments\n");
}
return 0;
}
阅读strncmp
和strcmp
。特别要确保知道为什么以及何时strncmp
优于strcmp
。