The main places of C ++ file control

so I start learning fileIO

. I am using a program called CodeRunner on my Mac and I have a folder containing:

validsudoku.cpp, validsudoku, sudokugood0.txt

The beginning of the code I wrote is:

int main(int argc, char const *argv[]){

//string filetoopen;
ifstream sudokutxtfile;
string txtline;
string sudokubox[9]; 
//bool goodsudoku = true;
//int i, j, row, column;

/*
if (argc == 2)
    filetoopen = argv[1];
else
    filetoopen = "sudokuboard.txt";
*/  

//read in file, save to array, close file
sudokutxtfile.open("sudokugood0.txt");  
while (getline(sudokutxtfile,txtline)) 
{
    sudokubox[row] = txtline;   
    row++;
}
sudokutxtfile.close();

      

Right now, to test this, I just have to open the file as "sudokugood0.txt"

, although as soon as I get this working, I'll change it to my variable 'filetoopen'

so that I can terminal enter the filename.

Now about my problem: When I run .cpp

in CodeRunner it looks at the file correctly .txt

and processes it, but when I put the executable and the file .txt

in the bin folder and try to run it from the terminal it doesn't see the file .txt

. Am I using the wrong location or am I missing something else?

Side question: it works on OSX, but in my Xubuntu VMbox using Codeblocks, which I have to use for the class, I get "Segmentation Fault (Kernel Dropping)" Does anyone know why? I have this at the top of my file for both:

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

      

+3


source to share


1 answer


The program tries to find the file you are opening in the current working directory, not in the location where the executable file is. When you run a program from the terminal, the current directory is the directory you are in. So if you do this for example. cd ~/

to go to your home directory and then run the program, the program will look for the file in your home directory. If you change to a different directory, the program will look for the file in that new directory.



The natural solution is to either pass the input file as an argument to the executable, or request it as input (I recommend the former).

+2


source







All Articles