无法打开文件流C ++ [英] unable to open file stream c++

查看:64
本文介绍了无法打开文件流C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Xcode,但无法打开文件流来分配文本文件中的变量.我推测将txt文件放置在与项目相同的目录中将使我可以在不包含整个目录的情况下打开流.我已经把它弄乱了好一阵子,但无济于事,我无法使其正常工作.我相信我能够一次读取数据,但是我认为打印的字符串是unicode(不确定).这是一个非常简单的程序.我认为它会起作用.我认为我的问题与示例所在的目录以及Xcode如何处理项目文件有关.我只是将示例文件放在项目文件夹中,希望它能工作.

I am working with Xcode and I am having trouble opening a file stream to assign variables from a text file. I speculate that placing the txt file in the same directory as the project would allow me open the stream without including the entire dir. I have been messing with this for a little while to no avail can I get it to work properly. I believe I was able to read data at one point, but I think the string printed was in unicode (not sure). It is a very simple program.. I would think that it would work. I think my problem has to do with the directory the example is in and how Xcode works with project files. I just put the example file in the project folder and hoped that it would work.

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

using namespace std;
int main()
{
    string name;
    ifstream infile;
    infile.open("example.txt");
    if(infile.is_open())
    {
        infile >> name;
    }
    else
        cout << "Unable to open file";

    cout << name;
    return 0;
}

推荐答案

首先,请记住,工作目录并不总是与程序二进制文件所在的目录相同.

First of all, remember, that working directory is not always the same directory where the program's binary resides.

更改:

infile.open("example.txt");

收件人:

infile.open("/full/path/to/program/directory/example.txt");

其中/full/path/to/program/directory/是文件夹的位置,程序(以及 example.txt 文件)的放置位置.它应该可以解决问题.

where /full/path/to/program/directory/ is the location of folder, where program (and thus example.txt file) is placed. It should fix the issue.

顺便说一句,您可能还想阅读

By the way, you may also want to read this question, that addresses very similar problem.

此外,请阅读 getcwd()函数

Also, read about getcwd() function.

这篇关于无法打开文件流C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆