2014-07-07 56 views
0

我有一个文本文件,名称为约800个文件,我想从一个文件夹传输到另一个文件夹。基本上,文本文件看起来像这样:如何在UNIX下使用(C)将文件从一个文件夹传输到另一个文件夹?

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; 
} 

现在,当我打印的文件路径,我得到预期的结果,但程序在运行'rename'函数时会停止运行,因为参数问题无效。 我看着http://www.cplusplus.com/,注意到它说rename()的参数应该是const char *,难道这是问题的来源吗?但是如果是这样,我不明白我怎样才能将我的参数变成'const',因为我在阅读我的初始文本文件时需要更新它们。

+1

你解决了一个普遍问题,还是你真的只想复制一组文件?您的操作系统将拥有*远远优越的*工具。 –

+0

是否想编写C或C++代码? – TWE

+1

使用您的操作系统的外壳。你将在十分钟内完成这项工作。这应该有所帮助:[使用FOR命令复制文本文件中列出的文件](http://www.sidesofmarch.com/index.php/archive/2004/03/30/using-the-for-command-to -copy-files-listed-in-a-text-file /) – Krumia

回答

0

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

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

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

+0

感谢您澄清常量事情的工作原理。 文件路径是正确的,据我所知,通过打印他们 – Nicolas

相关问题