File isn't being read? (C++) - c++

I am attempting to read numbers from a text file into a program, but for some reason, the program isn't reading the file. Here is my code:
#include <iostream>
#include <stream>
using namespace std;
int main()
{
ifstream infile;
infile.open ("adventDay1.txt");
if (!infile) { //Check if file is opening
cerr << "Error!"<< endl;
return 0;
}
int dataSize = 0;
infile >> dataSize;
int* arr;
arr = new int[dataSize]; //dynamically allocated array
int measureCount = 0; //Keep track of input from file
for (int i = 0; i < dataSize; i++) {
// infile >> dataSize;
arr[i] = dataSize;
measureCount += 1;
}
cout << measureCount << endl;
delete[] arr; //Delete dynamically allocated memory
return 0;
}
Each time I run it, it just displays the "Error!" message I added. There are 2,000 numbers in the text file, so that should be the expected output based on what I have here. I can't pinpoint the mistake.

Include fstream and ensure that you are opening the file in read mode. Perhaps also define it as ifstream infile("adventDay1.txt")

Related

How do I store a txt file into a char array?

I'm looking to store a txt file with 52 characters that have no spaces into a char array. What I have below only outputs garbage. I would appreciate on some insight on how to solve this.
`
int main()
{
fstream fin, fout;
int maxSize = 9999; // Max length for text file.
int sizeArray = 0; //Stores length of message.txt file.
char storeCharacter[maxSize]; //Array that stores each individual character.
fin.open("message.txt");
if(fin.fail())
{
cout << "Input file failed to open (wrong file name/other error)" << endl;
exit(0);
}
sizeArray = fileLength(fin, storeCharacter, maxSize); //Assigns size using fileLength function.
cout << sizeArray << endl;
char txtCharacters[sizeArray];
storeInArray(fin, txtCharacters, sizeArray);
for(int i=0; i<=sizeArray; i++)
{
cout << txtCharacters[i];
}
fin.close();
fout.close();
return 0;
}
int fileLength(fstream& fin, char storeCharacter[], int length)
{
char nextIn;
int i = 0;
fin >> nextIn;
while(!fin.eof())
{
storeCharacter[i] = nextIn;
i++;
fin >> nextIn;
}
return i; //returns the file size.
}
void storeInArray(fstream& fin, char arr[], int length)
{
int i = 0;
char nextIn;
while(!fin.eof() && i!=length )
{
fin >> nextIn;
arr[i] = nextIn;
i++;
}
}
`
I tried to use a while and for loop to store the txt file characters into a char array. I was expecting it to work since I have done a similar thing with a txt file full of integers. Instead garbage gets outputted instead of the contents of the text file.
first error here is that VLA is not a standard c++ feature. Do not use it
char txtCharacters[sizeArray];
also do not do
while(!fin.eof()
read Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
next
fileLength reads to the end of the file but you do not rewind the file after that. This function loads the file into an array anyway so why the read it (or try to) into a second array.
also
for(int i=0; i<=sizeArray; i++)
you mean
for(int i=0; i<sizeArray; i++)
way simpler is to read into std::vector, no need to calculate initial size. Just push_back each char
From the world of old-school, we use fopen, fread and fclose:
#include <stdio.h>
int read_file(const char* path, char* data, int max_length)
{
FILE *fp = fopen(path, "rb");
if (!fp) return 0;
int n = fread(data, 1, max_length, fp);
fclose(fp);
return n;
}
int main()
{
char data[1024] = { };
int l = read_file("message.txt", data, 1024);
printf("length = %d\n", l);
printf("text = %s\n", data);
return 0;
}
For the following message.txt (the alphabet twice with a trailing new line character, i.e. 26 + 26 + 1 = 53 bytes)
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
I get the following output:
length = 53
text = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
Somethings you'll note:
The read_file is implemented as a refactor of fopen, fread and fclose
We open the file in read-only binary mode
If the file didn't exist or there was a reason why we couldn't open, we early exit with 0 bytes read
We read up to a maximum of max_length and return the actual bytes read
We make sure we close the file before exiting
In the main I declare data as 1024 bytes, i.e. 1K which is more than enough
I ensure that the data has been zero-initialized, so, if nothing populates it, it will contain NUL characters
I use printf statements to display what has been read
To do the same thing using std::ifstream, I would simply make use of std::string and std::getline as follows:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin("message.txt", ios::in | ios::binary);
string data, line;
if (fin.is_open()) {
while (getline(fin, line)) {
data += line + "\n";
}
fin.close();
}
cout << "length = " << data.length() << "\n";
cout << "text = " << data << "\n";
return 0;
}

How to read a binary files and print 3's on screen?

I want to read a binary file of integer type and print the occurrence of the number of 3's in the file. I somehow wrote a program to open and read a binary file.
Here is the couple of problems I am facing:
If I try to print the file on my terminal, the execution continues
forever and the loop never ends.
I have no idea of how to filter out 3's from it.
Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
streampos size;
char * memblock;
ifstream file ("threesData.bin", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "the entire file content is in memory";
for (int i = 0; i < size; i += sizeof(int))
{
cout << *(int*)&memblock[i] << endl;
}
delete[] memblock;
}
else
cout << "Unable to open file";
return 0;
}
Here is a way to implement your requirements:
int main()
{
unsigned int quantity = 0U;
ifstream file ("threesData.bin", ios::in|ios::binary|ios::ate);
uint8_t byte;
while (file >> byte)
{
if (byte == 3U)
{
++ quantity;
}
}
cout << "The quantity of 3s is: " << quantity << endl;
return 0;
}
The first step should always get a simple version working first. Only optimize if necessary.
Allocating memory for a file and reading the entire file is an optimization. For example, your platform may not have enough available memory to read the entire file into memory before processing.

Creating array after getting variable in other function

A text file looks like this:
3
String
String2
String3
I must create a function to read all the strings from text file, save them to array and then display it in main function. For example
void reading(int & count, string strings[]) {
ifstream fd "text.txt";
fd >> count;
for (int i=0; i<count; i++)
fd >> strings[i];
fd.close();
And main function:
int main() {
int count=0;
string strings[100];
reading(count, strings);
for (int i=0; i<count; i++)
cout << strings[i] << endl;
The number of strings is written in first line of text file. How can I create an array of exactly that number? I need it to be able to access it in main/other functions. (For example function for writing into another text file).
In case there is a super important reason to do that with an array, then use std::new, like this:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int reading(string** str_array, int& size, string filename) {
ifstream infile(filename.c_str());
if(!infile) {
cerr << "Unable to access file!\n";
return -1;
}
int n = 0;
infile >> size;
try{
*str_array = new string[size];
string str;
for (; n < size && infile; ++n) {
infile >> str;
(*str_array)[n] = str;
}
if (n != size)
cerr << "ERROR, read less than " << size << " strings!!\n\n";
} catch(bad_alloc& exc) {
return -2;
}
return 0;
}
int main() {
string* str_array = NULL;
int size;
if(reading(&str_array, size, "test.txt")) {
cerr << "Din't read file, exiting...\n";
return -1;
}
for(int i = 0; i < size; ++i)
cout << str_array[i] << endl;
delete [] str_array; // DO NOT FORGET TO FREE YOUR MEMORY
str_array = NULL;
return 0;
}
Output:
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
String
String2
String3
However, you are in c++ and you are not using an std::vector for this?
Look how simple it is with that:
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int reading(vector<string>& v, string filename) {
ifstream infile(filename.c_str());
if(!infile) {
cerr << "Unable to access file!\n";
return -1;
}
int N = -1, n = 0;
infile >> N;
string str;
for (; n < N && infile; ++n) {
infile >> str;
v.push_back(str);
}
if (n != N)
cerr << "ERROR, read less than " << N << " strings!!\n\n";
return 0;
}
int main() {
vector<string> v;
if(reading(v, "test.txt")) {
cerr << "Din't read file, exiting...\n";
return -1;
}
for(size_t i = 0; i < v.size(); ++i)
cout << v[i] << "\n";
return 0;
}
Output:
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
String
String2
String3
Edit:
We have to pass a pointer to what we want to modify (that is, the string*), otherwise the changes we apply won't take place. Test it yourself, pass a string* as a parameter instead of string**, modify the body of the function and she what happens.
To get the idea, imagine we want to write to the pointer, the new address, which new gave us and holds the memory requested. We do write that address inside the function, but when the function terminates, we want the changes to be persistent. See my Functions in C as an example.
Allocate an array on the heap, like this:
std::string* stringArr = new std::string[(place amout of strings here)];
and don't forget to delete it at the end of main()
delete stringArr[];
Variables / arrays on the heap are dynamic so the size doesn't have to be fixed!
std::string* → This is a pointer that points to the address of the beginning of this array in your memory. (Just to let your computer know where it is)
stringArr → the name of the array
new → allocates new memory
std::string[size] → says how much to allocate
I've seen some answers that were talking about "vectors". If you wanna use them you could have a look at this page for more info! →
Vector documentation
use a vector
#include <vector>
#include<fstream>
#include <iostream>
using namespace std;
void reading(int & count, vector<string> * strings) {
ifstream fd("text.txt");
fd >> count;
string T;
for (int i=0; i<count; i++)
{
fd >> T;
strings->push_back(T);
}
fd.close();
}
int main() {
int count=0;
vector<string> strings;
reading(count, &strings);
for (int i=0; i<count; i++)
cout << strings[i] << endl;
}

C++ while, for and array

Hey guys I stuck working on an assignment in which I asked to write a program that lists the contents of a file.
#include<iostream>
#include<fstream>
using namespace std;
int main() {
string array[5];
ifstream infile("file_names.txt");
int x=0;
while(infile>>array[x++]){
for(int i=0;i<=x;i++){
infile >> array[i];
cout << array[i] << endl;}}
}
basically I have a file named "file_names.txt" that contains three strings and I want my program to list them.
you don't need two loops.
int main() {
int array_size=5;
string array[array_size];
ifstream infile("file_names.txt");
int x=0;int i=0;
while(i<array_size && infile>>array[i]){ //order is important here
cout << array[i] << endl;
i++;
}
}
Your assignment was
an assignment in which I asked to write a program that lists the contents of a file.
One way of printing the contents of a file could be
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin("my_file.txt", ios::in); // open input stream
if(!fin){ // check state, that file could be successfully opened
printf("Error opening file.");
return 1;
}
while(fin.peek() != EOF){
cout << (char)fin.get();
}
fin.close(); // close input stream
return 0;
}
This code demonstrates some basic C++ functionality like
opening an input stream, checking the state of the input stream and reading the contents character by character. Try to understand each step.
I know I can get to the same result like this
string array[50];
ifstream infile("file_names.txt");
for(int i=0; **i<3**; i++){
infile >> array[i];
cout << array[i] <<endl;}
But the whole point is to use a while loop because there might be more or less than 3 items

File Input failure C++

I've been trying to grasp how reading and writing with the fstream class works, and I've become stuck. The program reads the magic number of the file correctly, and then suddenly fails to read an integer. I'm guessing I am missing something very obvious, but after several Internet searches, I've come up with nothing. If someone could point out what I'm missing, it would be extremely appreciated. Thanks!
#include <fstream>
#include <iostream>
#include "File.h"
using namespace std;
const char magicnumber[8] = {'C','H','S','R','L','I','N','E'};
const int magiclength = 8;
void saveLines(char* filename, int linenum, Line* lines){
//Create the file and write the magic number to it
ofstream file(filename, std::ios::trunc);
for(int kkk = 0; kkk < magiclength; kkk++)
file << magicnumber[kkk];
//Write the number of lines we expect
file << linenum;
//Write the lines' data
for(int iii = 0; iii < linenum; iii++){
file << lines[iii].start.x << lines[iii].start.y;
file << lines[iii].finish.x << lines[iii].finish.y;
file << lines[iii].thickness;
}
cout << linenum << endl;
file.close();
}
Line* openLines(char* filename){
ifstream file(filename);
if(!file.is_open())
return NULL;
//Read the magic number of the file
char testnumber[12];
for(int jjj = 0; jjj < magiclength; jjj++)
file >> testnumber[jjj];
//Make sure the file contains the right magic number
for(int iii = 0; iii < magiclength; iii++){
if(testnumber[iii] != magicnumber[iii])
return NULL;
}
//Get the number of lines
int linenum = -1;
file >> linenum;
cout << linenum << endl;
if(linenum <= 0 || file.fail())
return NULL;
Line* product = new Line[linenum];
for(int kkk = 0; kkk < linenum; kkk++){
file >> product[kkk].start.x >> product[kkk].start.y;
file >> product[kkk].finish.x >> product[kkk].finish.y;
file >> product[kkk].thickness;
}
file.close();
return product;
}
In the openLines() function, the file opens correctly, and the magic number is read and matched correctly, but when the variable "linenum" is read, the file reads as gibberish, the fail() flag turns true, and the function returns NULL. If it matters, here's the Line struct:
typedef struct{
int x, y;
} Point;
typedef struct{
float slope;
float thickness;
Point start;
Point finish;
bool defined;
} Line;
I am using SDL in this project. I do not know if this matters, but I'm including it for completeness' sake. In cout.txt I get 2 (For the linenum when I'm writing the file) and then 2147483647 when I read it back. Thanks for looking!