无法在 cp 程序中打开文件

标签 c cp

我正在开发 cp 的自定义版本,其中参数是两个目录,第一个目录中的文件将复制到第二个目录。我当前的问题是打开第一个目录中的文件。当我到达代码的“打开文件”部分时,我收到一条错误,指出没有文件,这是没有意义的,因为文件名在错误中打印出来。我错过了一些简单的事情吗?我认为我包含了足够的代码。

int main(int ac, char *av[]) {    

int     in_fd, out_fd, n_chars;
char    buf[BUFFERSIZE];
struct stat sb;
DIR *copyFrom;
DIR *copyTo;
struct dirent *ep;

/* open dirs */
copyFrom = opendir(av[1]);
copyTo = opendir(av[2]);

while(ep = readdir(copyFrom))
{
    /* open files */
    if ( (in_fd=open(ep->d_name, O_RDONLY)) == -1 )
        oops("Cannot open", ep->d_name);

    if ( (out_fd=creat(ep->d_name, COPYMODE)) == -1 )
        oops( "Cannot create", ep->d_name);

    /* copy files */
    while ( (n_chars = read(in_fd , buf, BUFFERSIZE)) > 0 )
        if ( write( out_fd, buf, n_chars ) != n_chars )
            oops("Write error to ", av[2]);

    if ( n_chars == -1 )
        oops("Read error from ", av[1]);

    /* close files */
    if ( close(in_fd) == -1 || close(out_fd) == -1 )
        oops("Error closing files","");
}
}

最佳答案

readdir返回的DIR记录仅返回文件的基本名称。您需要将其与目录连接起来才能正确打开文件。

类似这样的事情:

char srcfile[1024];
sprintf("%s/%s", av[1], ep->d_name);
if ( (in_fd=open(srcfile, O_RDONLY)) == -1 )
        oops("Cannot open", srcfile);

关于无法在 cp 程序中打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28460595/

相关文章:

linux - 使用新的顺序名称复制文件 (Linux)

c - 字符串长度始终为 0

c - 复位 AVR 定时器溢出寄存器

c - 如何忽略或跳过数组中的某些字符并将数组的其余部分存储在 C 中?

c - 使用 doxygen 记录结构定义之外的 c 结构成员

Linux:如果目标目录不存在,则复制并创建它

使用 "cp"时的 Python 子进程错误

linux - CentOS:将目录复制到另一个目录

linux - 复制带扩展名的文件并按文件名排除

Android JNI - 如何正确释放在 C native 函数中分配的内存