c-如何知道重命名过程中哪个文件失败



我有一个简单的例子:

#include <stdio.h>
#include <errno.h>
int main() {
  int result = rename("filea", "doesntexist/fileb");
  if (result != 0) {
    printf("NOOOO %dn", errno);
  }
  return 0;
}

我想区分两种可能的故障:

  1. filea不存在
  2. fileb的目录不存在

但当两者都不存在时,它总是返回errno=2。。。嗯有什么想法吗?我该怎么做?

感谢

编辑:如果可能,无需手动检查文件是否存在。

EDIT2:不检查文件是否存在是一个愚蠢的约束;)所以,我已经接受了其中一个答案。谢谢

我不知道如何在不检查文件是否存在的情况下检查是否存在文件,但希望这个函数能帮助你:

#include <sys/stat.h>
if (!fileExists("foo")) { /* foo does not exist */ }
int fileExists (const char *fn)
{
    struct stat buf;
    int i = stat(fn, &buf);
    if (i == 0)
        return 1; /* file found */
    return 0;
}

如果你的目标是保持代码干净,那么只需使用函数:

int main() 
{
    if (! renameFiles("fileA", "fileB")) { 
        fprintf(stderr, "rename failed...n"); 
        exit EXIT_FAILURE; 
    }
    return EXIT_SUCCESS;
}
int renameFiles(const char *source, const char *destination)
{
    int result = -1;
    if ( (fileExists(source)) && (!fileExists(destination)) )
        result = rename(source, destination);
    if (result == 0)
        return 1; /* rename succeeded */
    /* 
        Either `source` does not exist, or `destination` 
        already exists, or there is some other error (take 
        a look at `errno` and handle appropriately)
    */
    return 0; 
}

您可以从renameFiles()返回自定义错误代码,并根据文件存在或不存在,或者rename()调用是否存在其他问题,有条件地处理错误。

首先调用access()(unistd.h)。或stat()。当filea不存在时,您可能会得到一个ENOENT错误。一些方法可以在文件B:上获得错误

  1. 找不到路径
  2. 路径上没有权限
  3. fileB存在,您没有权限
  4. 您的名称太长或格式不正确

还有其他的,但它们并不常见。

当fileB不存在时,不存在应该出现错误的情况。您执行mv filea-fileb(重命名的作用),mv的所有错误都适用于此。缺少目标文件不是其中之一。

你也应该有

#include <errno.h>

因为您引用了CCD_ 6。

ISO C标准甚至不要求库函数rename在出现错误时设置errno。所保证的只是错误时的非零返回值(7.19.4.2,§3)。

因此,这是否可能取决于您的平台(而且它不可移植)。

例如,在Linux中,只看rename之后的errno(根据本手册页)是无法区分它们中缺少的。

如果系统上的errno始终为2 ENOENT"No such file or directory",则必须检查是否存在某些内容。在我的系统上,如果old不存在,或者new的目录路径不存在,我会得到错误号2。

然而,可能出现的错误远不止2个。链接http://man.chinaunix.net/unix/susv3/functions/rename.html指定了20个不同的errno值。

我建议,如果重命名失败,错误号为2,则检查是否存在。如果找到,那么问题是new中指定的目录不存在。

最新更新