如何在c中将文件从一个目录移动到另一个目录?

时间:2014-04-04 07:14:08

标签: c file-io

我正在创建一个关于移动目录文件的项目,方法是根据c中的特定类型创建子文件夹。我已经在POSIX库{{1}的帮助下创建目录了。对于主目录中存在不同扩展名的文件,但我不知道如何从主目录中剪切文件并粘贴到其特定的子文件夹中。所以请指导我如何才能{{1} }和dirent.h cut中一个目录到另一个目录的文件。

1 个答案:

答案 0 :(得分:-1)

使用

重命名(DestinationFilepath,SourceFilepath);

了解更多信息请查看手册页http://linux.die.net/man/2/rename

对于两个不同的系统使用cURL库。 http://en.wikipedia.org/wiki/CURL

C中的代码

#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <time.h>

#define DESTINATION_FOLDER "/home/second/"
#define SOURCE_FOLDER "/home/first/" 

void printdir()
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;
    struct tm      *tm;

    char src_folder[1024];
    char dest_folder[1024];


    if((dp = opendir(SOURCE_FOLDER)) == NULL) {
         fprintf(stderr,"cannot open directory: %s\n", SOURCE_FOLDER);
         return;
    }
    chdir(SOURCE_FOLDER);
    while((entry = readdir(dp)) != NULL) {
        lstat(entry->d_name,&statbuf);

        if(!S_ISDIR(statbuf.st_mode)) \
        {
             sprintf(src_folder,"%s%s", SOURCE_FOLDER,entry->d_name); 
             sprintf(dest_folder,"%s%s", DESTINATION_FOLDER,entry->d_name); 
             printf("%s----------------%s\n",entry->d_name,dest_folder);
             rename(src_folder, dest_folder);
        }
    }
    chdir("..");
    closedir(dp);
}

int main()
{
    while(1)
    {
        printdir();
     }
    rename("aaa.txt", "/home/second/bbb.txt");
    printf("done.\n");
    exit(0);
}