简体   繁体   English

std::ifstream 和读取文件

[英]std::ifstream and reading files

So I've been stuck with a problem for a while now and I can't figure out why it's not working.所以我已经被一个问题困住了一段时间,我不知道为什么它不起作用。 It is probably something really stupid that I've forgotten about but I'm having a huge problem reading from a file located in my project.这可能是我已经忘记的非常愚蠢的事情,但是我在读取位于我的项目中的文件时遇到了很大的问题。

I'm trying to use "res/dir/file.txt" as a filepath but it wont work.我正在尝试使用“res/dir/file.txt”作为文件路径,但它不起作用。 I've also tried to move the file for "file.txt" filepath, but nothing.我还尝试移动“file.txt”文件路径的文件,但没有。 I've been moving the file around all over the project to see if can reach it from somewhere but with no success.我一直在整个项目中移动文件,看看是否可以从某个地方访问它,但没有成功。 The working directory is $(ProjectDir)工作目录是 $(ProjectDir)

streamFile("res/dir/file.txt");

My function looks something like this and I'm not able to enter the while loop with (getline(stream, line)) which is my major indicator to the problem:我的函数看起来像这样,我无法使用 (getline(stream, line)) 进入 while 循环,这是我解决问题的主要指标:

void streamFile(const std::string& filepath)
{
    std::ifstream stream(filepath);
    std::string line;
    while (getline(stream, line))
    {
        if (line.find("#Example") != std::string::npos)
        {

        }
        else
        {

        }
    }   
    return;
}

I feel really stupid atm because I know that I've done this before and never had a similar problem.我觉得 atm 真的很愚蠢,因为我知道我以前做过这件事,从来没有遇到过类似的问题。 What am I missing?我错过了什么?

Your code works perfectly fine.您的代码运行良好。 I tried it out this way:我是这样试的:

#include <iostream>
#include <fstream>

int main(void)
{
  std::ifstream stream("./res/dir/test.txt");
  std::cout << (stream.is_open() ? "file successfully opened" : "file could not be opened") << std::endl;
  std::string line;
  while (getline(stream, line))
  {
    std::cout << "line read: " << line << std::endl;
    if (line.find("my") != std::string::npos)
    {
      std::cout << "\t ... found magic word" << std::endl;
    }
    else
    {
      std::cout << "\t ... no magic word in this line" << std::endl;
    }
  }
}

./res/dir/test.txt ./res/dir/test.txt

hello world
my name is john doe
how are you?

The output is as expected:输出如预期:

file successfully opened
line read: hello world
     ... no magic word in this line
line read: my name is john doe
     ... found magic word
line read: how are you?
     ... no magic word in this line

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM