thomann061
thomann061

Reputation: 639

Trying to read a file into a char array

I am trying to read all the characters in a file into an array. Assuming all variables are declared, why are all the characters not being read into my array. When I output some of the characters in the "storeCharacters[]" array, garbage is being returned. Please help.

This is my function:

void countChars(ifstream& input, char storeCharacters[])
{
int i = 0;
    while( !input.eof() )
    {
        input.get(storeCharacters[i]);
        i++;
    }
}

Upvotes: 0

Views: 2142

Answers (3)

thomann061
thomann061

Reputation: 639

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>


using namespace std;


void getFileName(ifstream& input, ofstream& output)  //gets filename
{
string fileName;

cout << "Enter the file name: ";
cin >> fileName;
input.open(fileName.c_str());   
if( !input )
    {
        cout << "Incorrect File Path" << endl;
        exit (0);
    }
output.open("c:\\users\\jacob\\desktop\\thomannProj3Results.txt");
}

void countWords(ifstream& input)  //counts words
{
bool notTrue = false;
string words;
int i = 0;

while( notTrue == false )
{
    if( input >> words )
    {
        i++;
    }
    else if( !(input >> words) )
        notTrue = true;
}
cout << "There are " << i << " words in the file." << endl;
}

void countChars(ifstream& input, char storeCharacters[], ofstream& output)  // counts characters
{
int i = 0;

        while( input.good() && !input.eof() )
        {
                input.get(storeCharacters[i]);
                i++;
        }
        output << storeCharacters[0];
}

void sortChars()  //sorts characters
{
}

void printCount()  //prints characters
{
}

int main()
{

ifstream input;
ofstream output;

char storeCharacters[1000] = {0};

getFileName(input, output);
countWords(input);
countChars(input, storeCharacters, output);

return 0;
}

Upvotes: 0

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5428

The easy fix to your problem if you know the maximum size of your file, then just set your array to have that size and initialize it with \0.

let's say the maximum characters count in your file is 10000.

#define DEFAULT_SIZE 10000
char  storeCharacters[DEFAULT_SIZE];
memset (storeCharacters,'\0',DEFAULT_SIZE) ;

The below post should be the correct way to read a file using a buffer it has memory allocation and all what you need to know :

Correct way to read a text file into a buffer in C?

Upvotes: 0

Kara
Kara

Reputation: 6226

After the while loop try adding storeCharacters[i] = '\0' to null terminate the string.

Upvotes: 2

Related Questions