从不能使用C ++的文件中读取字符串

时间:2014-10-21 12:40:54

标签: c++ ifstream

我在C ++中有这段代码:

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

using namespace std;

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

我在file.txt的同一目录中有main.cpp。我没有得到任何输出,我已经尝试指定文件的完整文件路径,但仍然没有结果,并在几台不同的机器上尝试过。 有人知道我做错了吗?

1 个答案:

答案 0 :(得分:2)

您感兴趣的是您的计划的current working directory,例如,如果您没有使用完整路径或相对路径对其进行限定,那么您的文本文件应该在哪里。

您可以使用getcwd(linux)或_getcwd(windows)在运行时获取它。

编辑:我同意Andy,你应该在打开文件时检查错误。你可能早先发现了这个(例如找不到文件),例如

(为了说明目的,将伪代码提前)

#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
    }
    // ...
}