【问题标题】:How to move the files from one directory to another in c?如何在c中将文件从一个目录移动到另一个目录?
【发布时间】:2014-05-16 08:50:12
【问题描述】:

我正在创建一个移动目录文件的项目,方法是根据c 中的特定类型创建子文件夹。我已经在POSIXdirent.h 的帮助下为具有以下内容的文件创建目录主目录中存在不同的扩展名,但我不知道如何从主目录中剪切文件并粘贴到其特定的子文件夹中。所以请指导我如何cutpaste 来自一个目录的文件c 中的另一个人。

【问题讨论】:

标签: c file-io


【解决方案1】:

使用

重命名(目标文件路径,源文件路径);

更多信息请查看手册页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);
}

【讨论】:

  • 这只有在源和目标位于同一分区时才有效。
  • @someone 请给我一些 lstat() 函数的参考。
猜你喜欢
  • 1970-01-01
  • 2019-09-26
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多