5

This is my code:

double loglikelihood = 0; 
double loglikelihood1 = 0;
double THRESHOLD = 5;
double c = THRESHOLD + 1; 

std::ofstream llh_file;
std::ofstream myfile;   
const char *path= "path_of_file_to_be_saved";
myfile = ( string(path) + flags.inference_result_file_.c_str() ); 

for (int iter = 0; c > THRESHOLD; ++iter) {     
    std::cout << "Iteration " << iter << " ...\n";  
    loglikelihood = 0; 

    llh_file.open(myfile.c_str() );
    loglikelihood += sampler.LogLikelihood(&document);
    llh_file << "THE LOGLIKELIHOOD FOR ITER " << iter << " " << "IS: " << loglikelihood << "\n";                  
    llh_file.close();    

I am a newbie to C++. I have a folder containing different file names. I want to do some process in the for loop and save the results in the folder with the exact file names as the input files. How do I do it? Please help!

4
  • 3
    Read more about Programming using C++; use C++11 at least; learn about std::string, see here Commented Feb 2, 2016 at 9:08
  • 1
    Once you've done that, check out Boost.Filesystem. Commented Feb 2, 2016 at 9:09
  • Folders are OS specific; POSIX and Linux have directories, not folders. You could have a C++ implementation without any kind of folder (and even without directories). On POSIX, consider readdir(3) etc... & nftw(3) Commented Feb 2, 2016 at 9:10
  • See this. Maybe I am nitpicking, but if you googled on "read directory" you'll immediately find what I mention. Your question should mention what operating system you are interested in. Or consider POCO or Qt. BTW C++11 does not know about folders or directories. Commented Feb 2, 2016 at 9:15

1 Answer 1

5

To concatenate strings. Use std::string instead of char*. like:

#include <string>
#include <iostream>
#include <fstream>
int main() {
    std::string path = "path";
    std::string file = "file.txt";
    std::string myfile = path + "/" + "file.txt";
    std::string fname = "test.txt";
    std::ofstream f(fname);
    f << myfile;
}

this will write "path/file.txt" in the file named test.txt.

Sign up to request clarification or add additional context in comments.

3 Comments

this is exactly what I want. But, I want to save it in a file. This is printing the output. How to save it in a file as the input file name? The input file is in flags.inference_result_file_.c_str(). I am trying to save it in a file.
edited to write a string in a file. But you will have to adapt it to your code. I won't do all your job :)
hehe.. I figured it out ;) Thanks for the help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.