【发布时间】: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';在使用“文件名”之前你必须去掉它