Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用stat in/bin搜索文件_C_Unix_Stat_Bin - Fatal编程技术网

C 使用stat in/bin搜索文件

C 使用stat in/bin搜索文件,c,unix,stat,bin,C,Unix,Stat,Bin,嗨,我正在尝试写一个代码来搜索/bin目录中的文件,并确定该文件是否确实存在,我的代码总是出错,我真的不明白为什么你能给我一个线索 #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #define MAX 4096 int m

嗨,我正在尝试写一个代码来搜索/bin目录中的文件,并确定该文件是否确实存在,我的代码总是出错,我真的不明白为什么你能给我一个线索

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h> 
#include <sys/types.h>
#include <sys/stat.h>
#define MAX 4096

int main() 
{  
    while(1)
    {
       char input[MAX];
       struct stat buf;
       const char *space=" ";
       fgets(input, MAX, stdin);
       char *token;
       token = strtok(input, space);

            if (!strncmp(token,"/bin/",5))
                {    
                    if (stat(token,&buf)==-1)
                    {
                       perror(token);
                       printf( "ERROR\n");
                    }
                    else
                    {  
                 printf("FILE EXISTS\n");     
                    }  
                 }
    }
 return 0;
}   
免责声明:我刚刚更正了问题并添加了更多内容,以便你们更好地理解问题,不要对我大喊大叫。

来自:

如果新行被读取,它将被存储到缓冲区中

也就是说,代码当前尝试检查
“/bin/ls\n”
,而不是
“/bin/ls”

首先剥离尾随换行符进行修复。单向:

const char *delim = " \n";
fgets(input, MAX, stdin);
const char *token = strtok(input, delim);

请给出准确的测试输入。另外,请调用
perror
以获取错误案例中更详细的失败原因。@alk如果只有注释而没有错误,则完全可以answers@klutt:“完美”?好吧…@alk-Well,但至少它被认为是好的:)“被认为是好的”:我没有……谢谢,现在一切都很好
const char *delim = " \n";
fgets(input, MAX, stdin);
const char *token = strtok(input, delim);