AAA AAA - 11 months ago 46
C++ Question

creating multiple files from reading data from a file

I have written a c++ code to read from a file and create multiple files from there and write data into them. My input file is as follows:

1 2 3
2 3 4
3 4 5

the first digit of each line will be a file name and the following two digits are the data to be written into them. My code is as follows:

using namespace std;
ofstream os1;
FILE *fp;
int a;
int k1,k2;
char fileName[] = "0.txt";
fp=fopen("input.txt", "r");

while (fscanf(fp, "%d", &a) != EOF)
fscanf(fp, "%d", &k1);
fscanf(fp, "%d", &k2);
fileName[0]=a; (fileName);


But when I run the program, no file is created. Is there anything wrong in the code? how will I create the files?

Answer Source

When you read your "filename" with fscanf(fp, "%d", &a); the variable a will not contain an ascci value of '1' but an integer of binary value 1.

When you then set the first char of your filename with fileName[0]=a; the character will be '\x01` so a non printable character. This is prohibited in many filesystems, which will probably cause your opening to fail.

So, always check the state of the file to see if open succeeds.

By the way, why not use an ifstream for reading the file ?

int k1,k2;
string fileName = "0.txt";  
ifstream ifs("input.txt");

if (!ifs) {
    cerr << "Couldn't open input file" <<endl; 
    return 1; 

while (ifs >> fileName[0]) {    // note that you read a char, now 
    ifs >> k1 >> k2;
    ofstream os1(fileName);
    if (! os1) 
        cerr <<"Couldn't open output file "<<fileName<<endl; 
    else {
    } // closing is done automatically as os1 goes out of scope