Search code examples
c++fopenfreadcharacter-arrays

Create files from file names in another file C++


I am working on sorting several large files in C++. I have a text file containing the names of all the input files, one on each line. I would like to read the file names in one at a time, store them in an array, and then create a file with each of those names. Right now, I am using fopen and fread, which require character arrays (I am trying to optimize for speed), so my filenames are read into an array of character arrays. Those arrays, however, need to have a maximum size fixed in advance, so if the filename is smaller than the maximum, the rest is full of garbage. Then, when I try to use that array as the filename in fopen(), it doesn't recognize the file because it has garbage at the end of the string. How can I solve this problem? Here is my code:

 #include <iostream>
#include <fstream>
#include <string>
#include "stdafx.h"
#define NUM_INPUT_FILES 4

using namespace std;



FILE *fp;
unsigned char *buff;
FILE *inputFiles[NUM_INPUT_FILES];


int _tmain(int argc, _TCHAR* argv[])
{


    buff = (unsigned char *) malloc(2048);
    char j[8];
    char outputstring[] = "Feelings are not supposed to be logical. Dangerous is the man who has rationalized his emotions. (David Borenstein)";

    fp = fopen("hello.txt", "r");

    string tempfname[NUM_INPUT_FILES];
    //fp = fopen("hello.txt", "r");
    for(int i=0;i<NUM_INPUT_FILES;i++)
    {
        fgets(tempfname[i], 20, fp);
        cout << tempfname[i];
    }
    fclose(fp);

    for(int i=0; i<NUM_INPUT_FILES;i++)
    {
        fp = fopen(tempfname[i], "w");
        //fwrite(outputstring, sizeof(char), sizeof outputstring/sizeof(char), fp);
        if(fp)
        {
            fclose(fp);}
        else
            cout << "sorry" << endl;
    }


    return 0;
}

Also, how do I find the size of a buffer to write it out with fwrite()?

Thank you very much, bsg


Solution

  • As Don Knuth said, premature optimization is the root of all evil.

    Your filenames are definitely not the bottleneck! Just use std::string for them.

    You'd need to replace fp = fopen(tempfname[i], "w"); with fp = fopen(tempfname[i].c_str(), "w"); however.