Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read .txt files from C++ program in Xcode

Tags:

c++

file-io

xcode

I have been struggling on getting my C++ program to read my .txt file from Xcode. I even tried putting the .txt file in the same directory of my Xcode C++ program but it won't read from it successfully. I am trying to fill the dnaData array with all the nucleotides in the file, so I only have to read it once and then I can just operate on that array. Below is just a part of my code that handles the file. The idea of the whole program is to write a program that reads an input file (dna.txt) containing DNA sequences, analyzes the input in various ways, and outputs several files containing various results. The maximum number of nucleotides (see Table 1) in the input file will be 50,000. Any suggestions please?

#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
like image 509
dnadri Avatar asked May 09 '26 14:05

dnadri


1 Answers

I suspect the problem here is not with the C++ code, but with the file location. In Xcode, the binary programs are built in an Executables location. You have to set up the build phases to copy your input file to the Executables location. See this Apple Documentation

like image 79
CHardnett Avatar answered May 12 '26 05:05

CHardnett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!