You are here:

C++/place text file in certain location

Advertisement


Question
Hi,

My program can create text files with different names each time the loop runs based on certain input information. My piece of code for this purpose is:
[......]
         printf("Enter Test Identity: ");
     gets(obj.testId);
         
         std::ostringstream os;
         os << obj.testId << ".txt";
         ofstream Students(os.str().c_str() , ios::out);
         Students << obj.name << "\n" << obj.age << "\n";
[.........]

My problem is that I want to place these files to a specific location. I can do that with a constant file name, but I don't know how to implement this with files created in the above fashion.

Thanks in advance.  

Answer
Dear Taimoor:
I am not sure this will work but...
To open a file try this:

 ofstream Students(os.str().c_str() , ios::out);

 Students.open ("test.txt");

 // >> i/o operations here <<
Students << obj.name << "n" << obj.age << "n";
[.........]

 Students.close();

You can name the file ( e.g. "test.txt") or use a variable to input the name.

http://www.cplusplus.com/reference/iostream/ofstream/open/

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Titus B. Ledbetter, Jr.

Expertise

C , MFC, Object Oriented, Artificial Intelligence

Experience

I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Education/Credentials
Master's Degree Computer Science from Johns Hopkins

©2016 About.com. All rights reserved.