简体   繁体   English

读取txt文件C ++时出错

[英]Error reading txt file c++

I have this code that suppose to read a txt file. 我有这段代码,应该读取一个txt文件。 But for some reason i am always getting *File not found that means that fileIn.fail() failed... 但是由于某种原因,我总是会得到*File not found ,这意味着fileIn.fail()失败了...

#include <iostream>
#include <string.h>
#include <fstream>
#include <sstream>
#include <stdio.h>


using namespace std;

int main ()
{
    string fileName;
    ifstream fileIn;
    bool x;

    cout << "enter file name \n";
    cin  >> fileName;

    fileIn.open(fileName);

    if(fileIn.fail())
    {
        cerr << "* File not found";
        return true;
    }

the file located in the same folder as my main.cpp file and named input.txt. 该文件与我的main.cpp文件位于同一文件夹中,名为input.txt。 I have tried to set the fileName hard coded but this also didn't work. 我试图将fileName设置为硬编码,但这也不起作用。 What is wrong with my code? 我的代码有什么问题?

here is the project: 这是项目:

在此处输入图片说明

Here is a checklist: 这是一个清单:

  1. Do you have permissions to read/access the file? 您是否具有读取/访问文件的权限?
  2. Are you the owner of the file?(Linux) 您是文件的所有者吗?(Linux)
  3. Are you giving the correct path, relative or absolute from the executable? 您是否从可执行文件中给出了正确的相对或绝对路径?

If the answer to any of these is a no, then that is where the problem lies, not just "file not found" error. 如果对这些问题的回答均为“否”,那就是问题所在,而不仅仅是“找不到文件”错误。

--EDIT-- - 编辑 -

@VladIoffe the executable I see there, is qustion2 and the relative path you have to give is ../input.txt and not input.txt @VladIoffe我在这里看到的可执行文件是qustion2 ,您必须提供的相对路径是../input.txt而不是input.txt

您应该使用文件名的绝对路径。

Absoulut path will always works. 绝对路径将始终有效。 But I hate full path I prefer relative path for a simple reason: code is more portable. 但是我讨厌完整路径,我更喜欢相对路径,原因很简单:代码更具可移植性。 If you run your program with input.txt in the same path of executable it will work. 如果您在相同的可执行文件路径中使用input.txt运行程序,则它将起作用。 But when you use an IDE you must set the current directory in the IDE settings. 但是,当您使用IDE时,必须在IDE设置中设置当前目录。

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

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