【问题标题】:How can I transfer files from one folder to another folder using (C) under UNIX?如何在 UNIX 下使用 (C) 将文件从一个文件夹传输到另一个文件夹?
【发布时间】:2014-07-07 08:42:48
【问题描述】:

我有一个文本文件,其中包含大约 800 个文件的名称,我想从一个文件夹传输到另一个文件夹。基本上,文本文件如下所示:

file1.aaa (End of line)
file2.aaa
..
etc

我使用互联网上每个人都建议的“重命名”功能制作了这段代码:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ( void )
{
    FILE *file = fopen ( "C:\\Users\\blabla\\ListOfFiles.txt", "r" );
    char path1[100] = "C:\\blabla\\folder1\\";
    char path2[100] = "C:\\blabla\\folder2\\";
    char *s1;
    char *s2;

    char line [20]; /* the file names won't be any longer than that */
    while(fgets(line, sizeof line,file) != NULL)
    {
        char *filePath1 = (char *) malloc((strlen(path1) + strlen(line) + 1) * sizeof(char));
        char *filePath2 = (char *) malloc((strlen(path2) + strlen(line) + 1) * sizeof(char));
        filePath1 = strcpy(filePath1, path1);
        filePath2 = strcpy(filePath2, path2);
        strcat(filePath1,line);
        strcat(filePath2,line);


       if (rename(filePath1, filePath2) != 0)
       {
           perror("wrong renaming");
           getchar();
       }

       free(filePath1);
       free(filePath2);

    }

    fclose (file);

    return 0;
}

现在,当我打印文件路径时,我得到了预期的结果,但是由于无效参数问题,程序在应该运行“重命名”函数时停止运行。 我查看了http://www.cplusplus.com/ 并注意到它说 rename() 的参数应该是 const char*,这可能是问题所在吗?但如果是这样,我看不出如何将我的参数转换为“const”,因为我需要在阅读初始文本文件时更新它们。

【问题讨论】:

  • 您是在解决一般问题,还是真的只想将文件集复制一次?您的操作系统将为此提供非常出色的工具。
  • 想写 C 或 C++ 代码吗?
  • 使用操作系统的外壳。你会在十分钟内完成这项工作。这应该会有所帮助:Using the FOR command to copy files listed in a text file
  • 目标文件夹是否存在?是空的吗?如果没有,你能覆盖吗?
  • `fgets() 在读取字符串中保留 '\n';在使用“文件名”之前你必须去掉它

标签: c file directory


【解决方案1】:

构建文件路径的代码非常复杂,但应该可以工作。为了简化它,删除malloc() 并只使用两个静态大小的数组。另外,对于未来,please don't cast the return value of malloc() in C

你误解了const 的意思,这意味着rename() 不会改变它的两个参数指向的字符。这是一种说法,“这两个指针指向仅输入到此函数的数据,不会尝试从函数内部修改该数据”。如果可能,您应该始终使用const 参数指针,这有助于使代码更加更清晰。

如果您收到“无效参数”,这可能意味着找不到文件。打印出文件名以帮助您验证。

【讨论】:

  • 感谢您澄清 const 的工作原理。据我所知,文件路径是正确的
【解决方案2】:

我建议你看看:

How can I copy a file on Unix using C?

并在该代码中将“/bin/cp”替换为“/bin/mv”。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2013-05-21
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多