I am supposed to write a program that displays the first 10 lines of a file. I have a file named "characters.txt" in the same folder that my .cpp is saved in, but when I try to compile the program, it says the file cannot be found. Here is my code:

#include <iostream>
#include <fstream>
#include <cstdlib>

int main()

{
ifstream file; // in file an ifstream object
char word[250];
file.open("characters.txt");

if (!file.is_open())

{
exit(EXIT_FAILURE);
}

int counter = 0;

while (counter < 10 && file.good() ) // while input good and not at eof

{
file.getline(word, 250);
counter++;
cout << word << endl;
}

if (counter < 10) // if fewer than 10 lines

{
cout << "\nThe entire file was read.\n";
}

cout << "We read " << counter << " lines today.\n";
cout << "Press enter to exit.\n";

cin.get(word, 250);

return 0;

}

When you run a program, it has what is knwon as a "working directory". This is the place you can effectively think of the program, as the name implies, working in. This is where it will look for files to open, by default. This is where it will write files to, by default.

Because you have told your program to open the file "character.txt" without specifying where on the hard drive to find that file, it will look in the working directory.

The working directory is often, but not always, the same directory that the executable is in. As nathanOliver says, try putting the file "character.txt" in the same directory as the executable.

The cpp file is meaningless once the program has been created, and has nothing to do with it, so putting "character.txt" next to the cpp file is not goign to work unless your executable happens to be there as well.

Alternatively, give your program something more to work with; the complete location of the file. On windows, something like:

file.open("C:/the/complete/directory/path/to/characters.txt");

Edited 2 Years Ago by Moschops

This would depend on the IDE you are using. It will usually be somewhere within the project's directory, i.e., near the cpp file, but not exactly in the same directory. Look for a directory named either "Release" or "Debug", or even "build".

Alternatively, just make a file search for the executable file.

ofstream myfile;
    myfile.open(dirLog, std::ios_base::app);

        if(!myfile)
        {

        return FALSE;
        }

change 'dirLog' with your directory file path

This article has been dead for over six months. Start a new discussion instead.