在Xcode的C++程序中读取.txt文件

3

我一直在努力让我的C++程序从Xcode读取我的.txt文件。 我甚至尝试将.txt文件放在与Xcode C++程序相同的目录中,但它无法成功读取。我正在尝试使用文件填充dnaData数组,以便我只需要读取一次文件,然后就可以对该数组进行操作。下面是处理文件的代码的一部分。整个程序的想法是编写一个程序,读取包含DNA序列的输入文件(dna.txt),以各种方式分析输入,并输出几个包含各种结果的文件。输入文件中核苷酸(见表1)的最大数量将为50,000。 请有什么建议吗?

#include <fstream>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

const int MAX_DNA = 50000;

// Global DNA array. Once read from a file, it is
// stored here for any subsequent function to use
char dnaData[MAX_DNA];

int readFromDNAFile(string fileName)
{
int returnValue = 0;

ifstream inStream;
inStream.open(fileName.c_str());

    if (inStream.fail())
    {
        cout << "Input file opening failed.\n";
        exit(1);
    }

    if (inStream.good())
    {
        char nucleotide;
        int counter = 0;
        while ( inStream >> nucleotide )
        {
            dnaData[counter] = nucleotide;
            counter++;
        }
        returnValue = counter;
    }

    inStream.close();
    return returnValue;
    cout << "Read file completed" << endl;

} // end of readFromDNAfile function

2
输出是什么,程序是否成功结束? - Alper
使用std::vector。这里不需要使用固定数组,这只会让事情更加复杂。 - lethal-guitar
“但它无法成功读取”并不是很具体。请解释您遇到的错误/问题/意外输出等。 - lethal-guitar
不知道错误是什么,因为您没有在帖子中提供详细信息,但请检查您的文件位置 - XCode 项目的工作目录可能会很复杂。 - Pete855217
3个回答

4

我怀疑问题不在于C++代码,而是文件位置。在Xcode中,二进制程序被构建在可执行文件的位置。您需要设置构建阶段将输入文件复制到可执行文件位置。请参阅这个 苹果文档


0

我最近做了类似于你正在尝试的事情,使用了一个vector,代码如下:

vector<string> v;
// Open the file
ifstream myfile("file.txt");
if(myfile.is_open()){
    string name;
    // Whilst there are lines left in the file
    while(getline(myfile, name)){
        // Add the name to the vector
        v.push_back(name);
    }
}

上述代码读取文件中每行存储的名称,并将它们添加到向量的末尾。因此,如果我的文件有5个名称,那么会发生以下情况:

// Start of file
Name1    // Becomes added to index 0 in the vector
Name2    // Becomes added to index 1 in the vector
Name3    // Becomes added to index 2 in the vector
Name4    // Becomes added to index 3 in the vector
Name5    // Becomes added to index 4 in the vector
// End of file

尝试一下,看看它对你有什么作用。

即使您不按照上面显示的方式进行,我仍然建议在此情况下使用std::vector,因为向量通常更容易处理,而且没有理由不这样做。


0
如果每行只包含一个字符,那么这意味着你也将换行符('\n')读入DNA数组中。在这种情况下,可以使用以下方法:
while ( inStream >> nucleotide )
{
        if(nucleotide  == '\n')
        {
              continue;
        }
        dnaData[counter] = nucleotide;
        counter++;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接