简体   繁体   English

将多个文本文件从一个文件夹复制到C ++中的不同文件夹中

[英]copy multiple text files from a folder into different folders in C++

I have made a samll c++ program to copy multiple files from a folder to some other folders. 我做了一个samll c ++程序,可以将多个文件从一个文件夹复制到其他一些文件夹。 For example: I have 2 files named 0.txt and 1.txt in a input folder and I want to copy 0.txt to a folder named 1 and 1.txt to a folder named 2 (these folders are previously made). 例如:我在输入文件夹中有2个名为0.txt和1.txt的文件,我想将0.txt复制到名为1的文件夹,并将1.txt复制到名为2的文件夹(这些文件夹是先前制作的)。 My sample code is as follows: 我的示例代码如下:

#include <iostream>
#include <windows.h>
#include <stdio.h>
#include<stdlib.h>
#include<fstream>
#include <sstream>
using namespace std;

#define upper_bound 1  // total number of folders starting from 0

std::string to_string(int i) {
   std::stringstream s;
   s << i;
   return s.str();
}

int main()
{

for( int i=0;i<=upper_bound;i++)
{
    string s = ".\\input";
    string s1=".\\";
    string p= ".txt";
    string Input = s;
    string CopiedFile = to_string(i)+p;
    string OutputFolder = s1+to_string(i);
    CopyFile(Input.c_str(), string(OutputFolder+CopiedFile).c_str(), TRUE);
}

} 

But when I run it, nothing is copied. 但是当我运行它时,什么也不会被复制。 is there anything wrong in this? 这有什么问题吗? How will I copy those files? 我将如何复制这些文件?

You're trying to copy the file ".\\input.txt" to ".\\1\\1.txt 您正在尝试将文件“。\\ input.txt”复制到“。\\ 1 \\ 1.txt”

  1. input.txt might not exist in the current directory; input.txt在当前目录中可能不存在; try setting this to an absolute path 尝试将其设置为绝对路径

  2. You never create the directory "1" (again in the random working directory). 您永远不会创建目录“ 1”(同样在随机工作目录中)。 The documentation doesn't say that it will create the directory for you if it doesn't exist; 文档没有说如果不存在,它将为您创建目录。 so you should probably make sure that it does & create it if it doesn't. 因此,您可能应该确保它可以执行,否则请创建它。

This is the syntax of the function: 这是函数的语法:

BOOL WINAPI CopyFile(
 _In_ LPCTSTR lpExistingFileName, // absolute input path. 
 _In_ LPCTSTR lpNewFileName, // absolute output path
 _In_ BOOL    bFailIfExists  // to determine if you want to prevent the 
                             //file from being replaced
);

Your input path must be absolute. 您的输入路径必须是绝对的。 Your file's input path isn't absolute. 文件的输入路径不是绝对的。 It just addresses the file's directory and not the exact file. 它只是寻址文件的目录,而不是确切的文件。

Replace the below 替换以下

        string Input = s;

with: 有:

       string Input = s + String("\\") + to_string(i) + p; 

I have 2 files named 0.txt and 1.txt in a input folder 我在输入文件夹中有2个名为0.txt和1.txt的文件

So you must address both these files directly. 因此,您必须直接处理这两个文件。 But for each iteration the variable input only holds the string ".\\\\input" which is the directory and not the absolute path. 但是对于每次迭代,变量input仅包含字符串".\\\\input" ,这是目录,而不是绝对路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM