简体   繁体   English

检查文件是否在当前目录中

[英]Check if file exists in current directory

I'm using this piece of C code in Linux to check if file exists in the same directory as the ".c" file: 我在Linux中使用这段C代码检查文件是否与“ .c”文件位于同一目录中:

int file_exist(char *filename)
{
    FILE *fp = fopen(filename, "r");
    if (fp) {
        return 1;
    } else {
        return 0;
    }
}

but it always returns false even though the file exists! 但是即使文件存在,它也总是返回false! Is the problem that Linux is searching in a different directory? Linux在另一个目录中搜索的问题吗? How to solve this? 如何解决呢?

Just use stat - http://linux.die.net/man/2/stat 只需使用stat- http://linux.die.net/man/2/stat

If it returns 0 then the file exists. 如果返回0,则文件存在。 You can even find out if you can read it. 您甚至可以查找是否可以阅读。

Use ferror method to test everything is okay with input file. 使用ferror方法测试输入文件是否正常。

 FILE *fp;
 fp = fopen("RECORD.txt","r");

 if (ferror(fp) != 0){
  printf("File has error");
  exit(0);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM