简体   繁体   中英

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. 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). 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

  1. input.txt might not exist in the current directory; try setting this to an absolute path

  2. You never create the directory "1" (again in the random working directory). 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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