-2

Loop isn't making 10 copies and i have no idea how to change file names

#include "iostream"
#include "fstream"
#include "windows.h"
using namespace std;
void main()
{
        char str[200];   
        ifstream  myfile("as-1.txt");

        if (!myfile)
        {
            cerr << "file not opening";
            exit(1);
        }

        for (int i = 0; i < 10; i++)
        {

            ofstream myfile2("as-2.txt");
            while (!myfile.eof())
            {
                myfile.getline(str, 200);
                myfile2 << str << endl;
            }
        }
       system("pause");
}
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Your `ofstream` file name is hard-coded to be `as-2.txt` - it never changes. You need to use `i` to create a new file name each time through the loop. – BJ Myers Apr 26 '15 at 21:20
  • Please try to make your questions more than one line long! We would love much more information to help you. Thanks! – CinchBlue Apr 26 '15 at 21:21

2 Answers2

0

Solution using plain C API from <cstdio>. Easily customizable.

const char* file_name_format = "as-%d.txt"; //Change that if you need different name pattern
const char* original_file_name = "as-1.txt"; //Original file
const size_t max_file_name = 255;

FILE* original_file = fopen(original_file_name, "r+");

if(!original_file)
    //file not found, handle error

fseek(original_file, 0, SEEK_END); //(*)
long file_size = ftell(original_file);
fseek(original_file, 0, SEEK_SET);

char* original_content = (char*)malloc(file_size);
fread(original_content, file_size, 1, original_file);

fclose(original_file);

size_t copies_num = 10;
size_t first_copy_number = 2;
char file_name[max_file_name];

for(size_t n = first_copy_number; n < first_copy_number + copies_num; ++n)
{
    snprintf(file_name, max_file_name, file_name_format, n);
    FILE* file = fopen(file_name, "w");
    fwrite(original_content, file_size, 1, file);
    fclose(file);
}

free(original_content);

(*) As noted on this page, SEEK_END may not necessarily be supported (i.e. it is not a portable solution). However most POSIX-compliant systems (including the most popular Linux distros), Windows family and OSX support this without any problems.

Oh, and one more thing. This line

while (!myfile.eof())

is not quite correct. Read this question - it explains why you shouldn't write such code.

Community
  • 1
  • 1
Mateusz Grzejek
  • 11,698
  • 3
  • 32
  • 49
0
int main()
{
    const int copies_of_file = 10;
    for (int i = 1; i <= copies_of_file; ++i)
    {
       std::ostringstream name;
       name << "filename as-" << i << ".txt";
       std::ofstream ofile(name.str().c_str());
       ofile.close();
    }
    return 0;
}

That will make 10 copies of a blank .txt file named "filename as-1.txt" "filename as-2.txt" etc.

Note also the use of int main: main always has a return of int, never void

Tas
  • 7,023
  • 3
  • 36
  • 51