PDA

View Full Version : [Resolved] Access Source File's Location in C Source File?




ArtOfWarfare
May 18, 2013, 04:12 PM
I have a directory that looks like this:

(somewhere)/Project
(somewhere)/Project/project.xcodeproj
(somewhere)/Project/code/(all my source files)
(somewhere)/Project/input/(all my input files)
(somewhere)/Project/output/(empty right now)

Normally I just have Xcode copy all of my input files when it builds and any output goes to the console, but this time I want to output an output file for each input file.

(somewhere) is going to change because I'll be zipping this project up and submitting it as a school assignment. How can I ensure that the output folder that's alongside my project is properly output to?

I figure I need to be able to access the source code's location during the build. This sounded to me like a task for the preprocessor. Somehow it's capable of finding files via #include without being told the full path, which suggests to me there must be somewhere that it stores what the full path to the source file is, but thus far Googling hasn't turned up anything helpful.

Suggestions?

Edit: Wait... maybe __FILE__ is exactly what I want? Does this include the complete path name?

It's working on my computer with Clang, and from what I can tell it works with MinGW too, so I'm going to mark this as resolved.

2X Edit:

The exact solution to my problem:

I dropped in this header file called tinydir.h:
https://github.com/cxong/tinydir

Then in my program (this was a C++ project... I'm not sure how difficult changing it to straight C would have been.)

const unsigned int FOR_LOOP_MAXIMUM = 500; // a watchdog incase something is going wrong in the for loop

{
string sourceFilePath(__FILE__);
string projectPath = sourceFilePath.substr(0, sourceFilePath.rfind("code"));
tinydir_dir inputDir;
tinydir_open(&inputDir, (projectPath + "input").c_str());

for (unsigned int i = 0; i < FOR_LOOP_MAXIMUM && inputDir.has_next; i++)
{
tinydir_file inputFile;
tinydir_readfile(&inputDir, &inputFile);

string inputFilePath(inputFile.path);
if (inputFilePath.find(".input") != string::npos)
{
try
{
// read in the file
ifstream fin(inputFilePath);
knapsack knapsack(fin);

// solve the problem
greedyKnapsack(knapsack);

// when it returns, put the output in a file
string outputFilePath(inputFilePath);
replaceLast(outputFilePath, "input", "output");
replaceLast(outputFilePath, "input", "output");
ofstream fout(outputFilePath, ofstream::trunc);
knapsack.putSolutionIn(fout);
fout.close();
} catch (exception e) {
// I put the try-catch inside the for loop so that if one file
// throws an exception, the entire program won't abort
cout << "Exception Caught! Continuing..." << endl;
}
}

tinydir_next(&inputDir);
}

tinydir_close(&inputDir);
}