akalikin
akalikin

Reputation: 1127

Read string from a file not working C++

I have this code in C++:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
  string str;
  ifstream file("file.txt");
  file >> str;
  cout << str;
  return 0;
}

I have file.txt in the same directory as main.cpp. I get no output from this, I've tried specifying full filepath to the file and still no result and tried it on few different machines too. Does anybody know what I'm doing wrong?

Upvotes: 2

Views: 1707

Answers (1)

Marco A.
Marco A.

Reputation: 43662

What you're interested in is the current working directory for your program, i.e. where your text file is supposed to be if you don't qualify it with a full or relative path.

You can get it at runtime with getcwd (linux) or _getcwd (windows).

Edit: I agree with Andy, you should anyway check for errors when opening files. You could have caught this earlier (i.e. file not found), e.g.

(pseudocode ahead for illustrative purposes)

#include <unistd.h>

// Warning: linux-only, use #ifdefs and _getcwd for windows OS
std::string get_working_path() {
    char cwd[1024];
    if (getcwd(cwd, sizeof(cwd)) != NULL)
        return std::string(cwd);
    else
        return std::string("");
}

int main() {
    std::string str;
    std::ifstream file("file.txt"); 
    if (file >> str)
        std::cout << str;
    else {
        std::cout << "File not found in cwd: " << get_working_path();
        // abort
    }
    // ...
}

Upvotes: 3

Related Questions