我正在尝试编写自己的代码,以便在C编程中查找可执行文件作为学习练习。 (在成功之后,我可能会将其替换为别人的代码,但现在我想了解我的错误)。if statement ambiguity
下面的代码部分不跳转到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;
}
}
}
当我用gdb跟踪它,我看到它跳转到第2的其他不是第一个,和没有按“T执行检查可执行...
(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)
应该跳转到行32不是36
我已经试过searcing这里对于C模糊和我读过的‘C’的章节由Kernighan & Ritchie在C歧义下的索引中被引用,并且尽可能多地使用了花括号,但编译器并没有按照我的意图去做。
通知你,我在Fedora上使用gcc-4.5.1-4.fc14.x86_64内核2.6.35.14-106.fc14.x86_64 14
editor_stat.st_mode&EXECUTABLE的值是什么?可能,它只是通过代码正常,测试* if *,然后继续。你的代码被编译成与源代码不一致的代码,编辑器总是可以理解的简单方式 - 它不能完美地跟踪流,特别是如果你使用任何类型的优化进行编译。 – 2012-01-07 05:10:22
这不直接相关,但是你的条件语句更习惯性地写成'if'...'else if ... ... else'链,所有3个都在相同的缩进级别上。我无法在评论中显示格式。如果您需要更多解释,请告诉我,我会设置一个链接。 – 2012-01-07 05:58:24