【问题标题】:searching for files with stat in /bin在 /bin 中搜索带有 stat 的文件
【发布时间】:2021-04-25 18:59:41
【问题描述】:

您好,我正在尝试编写一个代码来搜索 /bin 目录中的文件并确定该文件是否实际存在,我的代码总是变成 ERROR,我真的不明白为什么你能给我一个线索?

#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

: No such file or directory
ERROR

免责声明:我刚刚更正了问题并添加了更多内容,以便你们更好地理解问题,不要对我大喊大叫。

【问题讨论】:

  • 请给出准确的测试输入。另外,请致电perror 以获取 ERROR 案例中更详细的失败原因。
  • @alk 只有cmets没有答案就完全OK了
  • @klutt:“完美”?嗯...
  • @alk 好吧,但至少它被认为是好的 :)
  • 认为可以”:不是我……

标签: c unix stat bin


【解决方案1】:

来自fgets manual

如果读取了换行符,则将其存储到缓冲区中。

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

通过首先去除尾随换行符来修复。一种方式:

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

【讨论】:

    猜你喜欢
    • 2012-08-24
    • 2019-03-17
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 2022-10-21
    • 2023-02-06
    相关资源
    最近更新 更多