ban*_*xxx 2 c compiler-construction if-statement
我正在尝试编写自己的代码来遍历PATH,以便在C编程中找到可执行文件作为学习练习.(成功后我可能会用别人的代码替换它,但是现在我想了解我的错误).
以下代码部分没有跳到我期望的else语句......
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define EXECUTABLE S_IXOTH /* executable by others */
#define MAX_PATH_LEN 1024
void message (const char *msg)
{
fprintf(stdout, "INFO: %s\n", *msg);
}
int main (int argc, char *argv[], char *envp[])
{
char *editor;
struct stat editor_stat;
char full_path[MAX_PATH_LEN];
int found_path;
memset(full_path,0,MAX_PATH_LEN);
strcpy(full_path,"/bin/ed");
found_path=stat(full_path,&editor_stat);
if (found_path!=0) {
editor=NULL;
message("The EDITOR specified is not found in the PATH. Using default editor");
} else {
if (editor_stat.st_mode&EXECUTABLE==0) {
editor=NULL;
message("The EDITOR specified must have world execute permission. using default editoe");
} else {
editor=full_path;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用gdb跟踪它时,我看到它跳转到第二个而不是第一个,并且不执行可执行文件检查...
(gdb) file /tmp/sample2
Reading symbols from /tmp/sample2...done.
(gdb) b 28
Breakpoint 1 at 0x400688: file /home/ken/c/shorter_sample.c, line 28.
(gdb) r
Starting program: /tmp/sample2
Breakpoint 1, main (argc=1, argv=0x7fffffffe1f8, envp=0x7fffffffe208)
at /home/ken/c/shorter_sample.c:28
28 if (found_path!=0) {
Missing separate debuginfos, use: debuginfo-install glibc-2.13-2.x86_64
(gdb) p found_path
$1 = 0
(gdb) s
36 editor=full_path;
(gdb)
Run Code Online (Sandbox Code Playgroud)
它应该跳到32行而不是36.
我已经尝试过在这里搜索C歧义,我已经阅读了Kernighan和Ritchie的"C"部分,这些部分在C模糊度下的索引中被引用,并且在代码中尽可能多地插入花括号但是编译器不是做我想做的事.
仅供参考,我在Fedora 14上使用内核2.6.35.14-106.fc14.x86_64的gcc-4.5.1-4.fc14.x86_64.
&运算符优先级低于==; 这意味着第二个if陈述相当于:
if (editor_stat.st_mode&(EXECUTABLE==0))
Run Code Online (Sandbox Code Playgroud)
我打算走出去,说EXECUTABLE是不是0,这if相当于:
if (editor_stat.st_mode & 0)
Run Code Online (Sandbox Code Playgroud)
要么
if (0)
Run Code Online (Sandbox Code Playgroud)
第二个if陈述应该是:
if ((editor_stat.st_mode&EXECUTABLE)==0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
172 次 |
| 最近记录: |